Script Logging

Most of my scripts have a very standard element. Logging!

My logging method has two parts, a script block and an invoke-command line. Its not the typical function call. Just a small piece to get started, and lay the support for recording what your script is going to do.

First we create a path for the log with date stamp
  $logLocation = "c:\beep\logs\$($MyInvocation.MyCommand.Name)_$(get-date -f "MM_dd").log"
 

The scriptblock has 2 parameters $msg and $quiet. Msg is the text you want to record in the log and Quiet is a switch that allows console output to be silenced. The block will loop until its able to change the updated variable, affectively retrying until the write completes or the counter reaches 5. Each line is date stamped. If not quiet then write the message to the console.

  $logMsg = {
    param([string]$msg,[switch]$quiet)
    $updated = $false
    $cnt = 0
    while(!$updated -or $cnt -ge 5)
    { try
      { "$(get-date -f "MM/dd/yyyy HH:mm:ss") - $($msg)" | Out-File $logLocation -Append}
      catch{$cnt ++}
      $updated = $true
    }
    if(!$quiet){$msg}
  }
#Call log routine 
Invoke-Command $logMsg -ArgumentList "Starting script: $($MyInvocation.MyCommand.Name)"


This simple block of code allows for multithreaded scripts to be able to log to a single file in a thread safer way. I say safer and not safe. There are other ways to implement a thread safe method. The idea with this is to just keep it simple and little extensible. Adding -asjob to the invoke-command would make this a separate job and even more thread safer.

No comments:

Post a Comment

Top Tech Talk

Datrium Experience (fin)

This series has discussed the performance, the ease of use, the resiliency, the flaws and the finale of the Datrium DVX platform. From here ...