Help formatting log output

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.

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.

Thanks a million Rob. You have been as usual very helpful :slight_smile:

 

Oops, totally meant to put a link in there:

Also, just a quick test shows that Get-Date is actually faster…

PS C:\Users\rasim> Measure-Command {
    Get-Date
}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 7
Ticks             : 76788
TotalDays         : 8.8875E-08
TotalHours        : 2.133E-06
TotalMinutes      : 0.00012798
TotalSeconds      : 0.0076788
TotalMilliseconds : 7.6788


PS C:\Users\rasim> Measure-Command {
    [datetime]::Now
}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 11
Ticks             : 114846
TotalDays         : 1.32923611111111E-07
TotalHours        : 3.19016666666667E-06
TotalMinutes      : 0.00019141
TotalSeconds      : 0.0114846
TotalMilliseconds : 11.4846

Thanks again Rob. I am going with

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.1087

 

PS 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