Logging in CMTrace format from PowerShell

I know there are other examples of doing this out there but the one I use has a few other features including:

  • Getting the PID of the PowerShell instance running and putting that in the Thread column
  • Renaming the file to lo_ once it gets too large
  • Setting a variable to the status of the script based on the logging (used to display whether the script had an error or not)
  • Logging to the current directory the script exists in
  • Verbose Logging as an option

Here is the code:

 function LogIt
{
  param (
  [Parameter(Mandatory=$true)]
  $message,
  [Parameter(Mandatory=$true)]
  $component,
  [Parameter(Mandatory=$true)]
  $type )

  switch ($type)
  {
    1 { $type = "Info" }
    2 { $type = "Warning" }
    3 { $type = "Error" }
    4 { $type = "Verbose" }
  }

  if (($type -eq "Verbose") -and ($Global:Verbose))
  {
    $toLog = "{0} `$$<{1}><{2} {3}><thread={4}>" -f ($type + ":" + $message), ($Global:ScriptName + ":" + $component), (Get-Date -Format "MM-dd-yyyy"), (Get-Date -Format "HH:mm:ss.ffffff"), $pid
    $toLog | Out-File -Append -Encoding UTF8 -FilePath ("filesystem::{0}" -f $Global:LogFile)
    Write-Host $message
  }
  elseif ($type -ne "Verbose")
  {
    $toLog = "{0} `$$<{1}><{2} {3}><thread={4}>" -f ($type + ":" + $message), ($Global:ScriptName + ":" + $component), (Get-Date -Format "MM-dd-yyyy"), (Get-Date -Format "HH:mm:ss.ffffff"), $pid
    $toLog | Out-File -Append -Encoding UTF8 -FilePath ("filesystem::{0}" -f $Global:LogFile)
    Write-Host $message
  }
  if (($type -eq 'Warning') -and ($Global:ScriptStatus -ne 'Error')) { $Global:ScriptStatus = $type }
  if ($type -eq 'Error') { $Global:ScriptStatus = $type }

  if ((Get-Item $Global:LogFile).Length/1KB -gt $Global:MaxLogSizeInKB)
  {
    $log = $Global:LogFile
    Remove-Item ($log.Replace(".log", ".lo_"))
    Rename-Item $Global:LogFile ($log.Replace(".log", ".lo_")) -Force
  }
} 

function GetScriptDirectory
{
  $invocation = (Get-Variable MyInvocation -Scope 1).Value
  Split-Path $invocation.MyCommand.Path
} 

$VerboseLogging = "true"
[bool]$Global:Verbose = [System.Convert]::ToBoolean($VerboseLogging)
$Global:LogFile = Join-Path (GetScriptDirectory) 'LogIt.log' 
$Global:MaxLogSizeInKB = 10240
$Global:ScriptName = 'LogIt.ps1' 
$Global:ScriptStatus = 'Success'

LogIt -message ("Starting Logging Example Script") -component "Main()" -type 1 
LogIt -message ("Log Warning") -component "Main()" -type 2 
LogIt -message ("Log Error") -component "Main()" -type 3
LogIt -message ("Log Verbose") -component "Main()" -type 4
LogIt -message ("Script Status: " + $Global:ScriptStatus) -component "Main()" -type 1 
LogIt -message ("Stopping Logging Example Script") -component "Main()" -type 1

 

CMTrace Output (Download CMTrace.exe here.)

 

image

LogIt.renametops1