PowerShell: Simple Logging
I wrote this function, probably about ten years ago, but recently updated it. The more we use scripts for automation and making changes in our environments, it is essential that we log the actions that our scripts take. The reason I wrote this as a function was I could embed it in any script and didn't have to worry about installing and importing modules. The function below is very simple and outputs a log that has the date and time, message type, and the message and dumps it out in a comma-delimited format that allows for easy import into excel and most tailing programs.
# Set Variables
$global:strLogFile = "MyLog.Log" # Include the full path to the log file, this can be a UNC path
$global:arrCache = @()
$global:intCacheCounter = 10 # Tracks how many items are in the log cache
$global:inCacheSize = 1 # Sets cache size, setting it to 1 will write each entry as it's created
Function funLog ($strType,$strMsg)
{
<# Logging
Writes a comma delimited log file that is similar to syslog format
Log format: Date & Time, Message Type, Message
Message type
Can store text or numeric values, I recommend using the syslog severity as it is easy to read,
the below table is the syslog standard
Value Severity Keyword
0 Emergency emerg
1 Alert alert
2 Critical crit
3 Error err
4 Warning warning
5 Notice notice
6 Informational info
7 Debug debug
Usage
funLog "Type" "Message"
Examples
funLog "Info" "The command worked"
funLog "Error" ("The following error " + $error + " was generated")
To flush the log set $global:intCacheCounter = "0"
#>
# Create log entry
$global:arrLogCache += (Get-Date -Format "MM-dd-yyTHH:mm:ss")+","+$strType+",`""+$strMsg+"`""
# Check to see if the cached should be written
if ($global:arrCacheCounter -eq $global:intCacheSize -or $intCacheCounter -eq 0)
{
# Write cache to file
Add-Content $global:strLogFile $global:arrLogCache
# Rest counter to 0
$global:intCacheCounter = 0
# Clear cache
$global:arrLogCache = @()
}
# Increase log counter
$global:intCacheCounter++
}