Skip to content

Powershell event logging tool

06/12/2012

This powershell function can be added to any script to allow logging to a text file. It allows each event to have a severity, and if you set a global debug level it will enable multi-level debug logging capability for the script.

It supports the usual get-help syntax that also contains a bunch of examples. The script picks up errors in $error so best to do an $error.clear() at the start of the script (a good idea as a matter of course).

<#
   .SYNOPSIS
   This function logs an input string to a text file prefixed by a
   date/time/severity.
   .DESCRIPTION 
   Takes string input from a parameter or the pipeline and writes to a logfile,
   with appropriate date/time information. Allows specification of an (optional)
   severity. The function supports a global debug level in the script, so that
   it can be passed a per-event debug value and will decide whether to log the
   event based on the global debug setting.
   
   Also writes the output to the console for the host script to be easily used
   interactively.
   
   The script catches powershell errors and logs these too (eg. in a try/catch
   block).
   
   You must specify the logfile path $sLogFile in your script. If this is not
   set, a logfile will be created in this user's temp directory:
   
   %TEMP%\writelog.log.
   
   You may optionally specify an integer debug level $iDebug in your script,
   then specify for each event the debug level for which that event will be
   logged.
   .PARAMETER eventText
   The text to log 
   .PARAMETER sev
   Severity. This appears in parentheses after the date/time. Convention
   suggests a single letter (although anything will be accepted) e.g.
   "E" = error, "W" = warning etc. Default is "I" (Informational).
   .PARAMETER noDate
   Writes eventText string without any date/time/severity preamble. e.g. for
   writing an initial title line of the logfile.
   .PARAMETER dbg
   Setting a value for this parameter will cause write-log to log the event
   ONLY if the value of the parameter is less than or equal to the global debug
   level $iDebug. e.g. if dbg is set to 2, write-log will only log this event
   if the global debug level is 2 or higher. Default for this is 0, i.e. log
   all messages.
   .EXAMPLE
   Write-Log "test event"
   writes to file:
     
   01-01-2011 14:34:32 (I) : test event
   .EXAMPLE 
   "test event 2" | Write-Log
   writes to file:
   
   01-01-2011 14:34:32 (I) : test event 2
   .EXAMPLE
   "test event error" | Write-Log -sev "E"
   writes to file:
    
   01-01-2011 14:34:32 (E) : test event error
   .EXAMPLE
   "test event 4" | Write-Log -noDate
   writes to file:
   
   test event 4
   .EXAMPLE
   write-log "event level 4" -dbg 4
   writes to file:
   
   01-01-2011 14:34:32 (I) : event level 4
   
   if the global debug level has been set to 4 or greater, or does nothing if
   the global debug level has been set to between 0 and 3. If the global debug
   level has not been set at all then the event will always be logged.      
   .EXAMPLE
   Write-Log -eventText "event 123","event 234"
   writes to file:
   
   01-01-2011 14:34:32 (I) : event 123
   01-01-2011 14:34:32 (I) : event 234
   .NOTES
   AUTHOR: Dan Johnson (dan@djjconsulting.com)

   UPDATED     VER   REASON FOR UPDATE
   ===================================
   05/03/2012  1.0   First Issue
   10/10/2012  1.1   Added debug levels
   06/12/2012  1.2   Improved pipeline handling

   .LINK
   http://dsablog.com
   .LINK
   http://djjconsulting.com
#>
Function Write-Log()
{

param(  
  [Parameter(Position=0,
             Mandatory=$false,
             ValueFromPipeline=$true,
             HelpMessage="Please enter string to log")]
  [String[]]$eventText,
  [Parameter(Position=1,
             Mandatory=$false,
             ValueFromPipeline=$false)]
  [String]$sev = "I",
  [Parameter(Position=2,
             Mandatory=$false,
             ValueFromPipeline=$false)]
  [int]$dbg = 0,
  [switch]$noDate
)

    begin
    {
        if ($noDate)
        {
            $sPreamble = ""
        }
        else
        {
            $sNow = Get-Date -Format "dd-MM-yyyy HH:mm:ss"
            $sPreamble = "$sNow ($sev) : "
        }
        
        if ($sLogFile -eq $null)
        {
            $sLogFile = "$env:temp\writelog.log"
        }
    }

    process
    {      
        foreach($item in $eventText)
        {
            if ($dbg -le $iDebug -or $iDebug -eq  $null)
            {
                $sLogEntry =  "$sPreamble$item"
                Write-Host $sLogEntry
                $sLogEntry | Out-File $sLogFile -append -encoding ASCII
            }
        }
    }
    
    end
    {
        if ($error.count -gt 0)
        {
            "$sNow (E) : ERROR" | Out-File $sLogFile -append -encoding ASCII 
            "`t`t" | Out-File $sLogFile -append -encoding ASCII 
            $error | Out-File $sLogFile -append -encoding ASCII
            "`t`t" | Out-File $sLogFile -append -encoding ASCII 
            $error.clear()|out-null
        }
    }
}

# ******************************************************************************

Advertisements

From → Powershell

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: