Skip to content

Instantly share code, notes, and snippets.

@NakedPowerShell
Created October 31, 2016 09:10
Show Gist options
  • Save NakedPowerShell/faeebcce66f664abbeacdbf977da67a8 to your computer and use it in GitHub Desktop.
Save NakedPowerShell/faeebcce66f664abbeacdbf977da67a8 to your computer and use it in GitHub Desktop.
Tweaks to Write-LogEntry that was posted to Twitter by Trevor Sullivan @pcgeek86
function Write-LogEntry {
[CmdletBinding()]
param (
[string] $Message,
[string] $Severity,
[string] $Step
)
$CallStack = Get-PSCallStack
$LogMessage = '{0},{1},{2},{3},{4},{5}' -f $env:computername,((get-date).ToUniversalTime()), $CallStack[1].FunctionName, $Severity, $Message, $Step
Add-Content -Path c:\temp\logfile.csv -Value $LogMessage
}
function LogTester {
[CmdletBinding()]
param (
)
Write-LogEntry -Message Testing1 -Severity Information -Step 10
Write-LogEntry -Message Testing2 -Severity Warning -Step 20
Write-LogEntry -Message Testing3 -Severity Error -Step 55
}
LogTester
@NakedPowerShell
Copy link
Author

I did the following:

Changed the format of the date to UTC that was readable by Excel
Changed the output to a .CSV format and adding commas to the -f
Added the computername as the first entry in the text log
Added a parameter Step to the log

When I am consuming logs, lots of logs, I like tools like Excel to slice, dice, sort, and filter the data for me in a visual way.

When I write logging functions, I like to know what step tripped the log entry. So in my applications I set $Step to a number that is incremental from the last step I used this variable.

For example I set my step to 10 for the variable initially at the beginning of the application. Then at the start of each major piece of logic where I could trip the logging I increment the step by 10.

The steps then help me narrow down where in code the logging got tripped.

A future version of this could be to load the log into a SQL Table and also account for multiple applications writing to the same log.

Thank Trevor !!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment