As far as I can tell, there are no logging APIs built into the PowerShell framework. So, when I have to write a code solution in PowerShell, I just add this snippet to meet some of my basic logging needs.
Set up some helper variables
I need to set the name and location of my log file. In addition, I like to add a “run id” to my logs so that I can easily group all the log entries associated with a given execution together for analysis or performance reporting:
$ExecutionDir = Split-Path $MyInvocation.MyCommand.Path
$RunId = ([guid]::NewGuid()).ToString().Replace("-", "")
$logFile = "$ExecutionDir\my_log.log"
Add my helper function
This simple helper function meets my basic logging needs:
function Write-Log($logMsg){
("{0}|{1}|{2}" -f ("{0:yyyy-MM-dd HH:mm:ss}" -f (Get-Date).ToUniversalTime()), $RunId, $logMsg) | Out-File $logFile -Append
}
Now, log away
Write-Log -logMsg "Starting up some script"
# do some work here
Sleep 2
Write-Log -logMsg "Finishing some script"
This produces a simple log like below. You can see my “run id” in the second column that helps me group log lines together by unique executions:
Sure, there are no log levels, no file rotations, no easy way to change the format…but in lieu of a built in API, this does the trick. One way it could be improved would be to stick this work into a module that I could simply import from script-to-script instead of copy/pasting this code around.
Recent Comments