Welcome › Forums › General PowerShell Q&A › Help formatting log output
- This topic has 4 replies, 2 voices, and was last updated 1 month, 1 week ago by
Participant.
-
AuthorPosts
-
-
December 10, 2020 at 2:00 pm #278499
I am trying to find the best method to format my PowerShell logging. What I am trying to achieve is the following. I want to precede all lines sent to the log file with the following:
[07-30-2020 17:15:44 -0700 INFO] yada yada yada ….
So, precede log entries with [month-day-year hours:minutes:seconds timezone INFO] similar to Splunk logging.
I have no problems getting this format, but it seems like a performance hit to calculate the date/time information for each line logged (of which there are many). Is there a better way then running Get-Date for each line logged?
I should also point out this is all run through Start-Transcript.
Thanks in advance for any help/suggestions.
-
December 10, 2020 at 2:09 pm #278505
Have you tried .NET methods? I would imagine that Get-Date is just a wrapper for these. Would have to use ToString() or string format after you have the date.
-
December 10, 2020 at 2:36 pm #278514
Thanks a million Rob. You have been as usual very helpful 🙂
https://docs.microsoft.com/en-us/dotnet/api/system.datetimeoffset?view=net-5.0
-
December 10, 2020 at 2:55 pm #278520
Oops, totally meant to put a link in there:
#PSTip Working with DateTime objects in PowerShell using [System.DateTime]
Also, just a quick test shows that Get-Date is actually faster…
PowerShell1234567891011121314151617181920212223242526272829303132PS C:\Users\rasim> Measure-Command {Get-Date}Days : 0Hours : 0Minutes : 0Seconds : 0Milliseconds : 7Ticks : 76788TotalDays : 8.8875E-08TotalHours : 2.133E-06TotalMinutes : 0.00012798TotalSeconds : 0.0076788TotalMilliseconds : 7.6788PS C:\Users\rasim> Measure-Command {[datetime]::Now}Days : 0Hours : 0Minutes : 0Seconds : 0Milliseconds : 11Ticks : 114846TotalDays : 1.32923611111111E-07TotalHours : 3.19016666666667E-06TotalMinutes : 0.00019141TotalSeconds : 0.0114846TotalMilliseconds : 11.4846 -
December 10, 2020 at 3:03 pm #278529
Thanks again Rob. I am going with
[DateTimeOffset]::Now
as it gets me both the Date/Time and the TimeZone in one command and I am including both in my log prefix.
My testing was a tad different then yours, just an FYI
PS C:\> Measure-Command {[DateTimeOffset]::Now}
Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 0
Ticks : 1087
TotalDays : 1.25810185185185E-09
TotalHours : 3.01944444444444E-08
TotalMinutes : 1.81166666666667E-06
TotalSeconds : 0.0001087
TotalMilliseconds : 0.1087PS C:\> Measure-Command {get-date}
Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 0
Ticks : 2985
TotalDays : 3.45486111111111E-09
TotalHours : 8.29166666666667E-08
TotalMinutes : 4.975E-06
TotalSeconds : 0.0002985
TotalMilliseconds : 0.2985
-
-
AuthorPosts
- You must be logged in to reply to this topic.