Simple PowerShell Logging Function

I use this simple PowerShell logging function in multiple smaller scripts of mine to write a hourly logfile with a generic name in a specific path.

As an input it takes the two parameters “message” and “severity”. The later is optional and set to “INFO” by default. It further needs the (global) variable $logPath which should be defined and filled with the full path to where the logfile should be stored on the filesystem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Define the log output directory
$logPath = "C:\temp\log"
 
# Simple Logging Function
function Write-Log(){
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)]
        [String]
        $message = "INFO",
 
        [Parameter(Mandatory = $false)]
        [ValidateSet("INFO","WARN","ERROR","DEBUG")]
        [String]
        $severity = "INFO"
    )
 
    # Define Output Color
    $color = "white"
    if($severity -eq "WARN"){
        $color = "yellow"
    }
    elseif($severity -eq "ERROR"){
        $color = "red"
    }
    elseif($severity -eq "DEBUG"){
        $color = "cyan"
    }
 
    # Create Log Directory if not exists
    if(!(Test-Path $global:logPath)){
        New-Item -ItemType Directory -Path $global:logPath
        Write-Log "Log Directory '$($global:logPath)' created"
    }
 
    # Prepare Log Line
    $logLine = "$(Get-Date -format "dd.MM.yyyy HH:mm:ss") `t $($severity) `t $($message)"
 
    # Write Logfile
    $scriptName = ((($MyInvocation.ScriptName -split ("\\"))[($MyInvocation.ScriptName -split ("\\")).Length -1]) -replace ".ps1", "").ToLower()
    $logFileName = "log_$($scriptName)_$(Get-Date -format "yyyy-MM-dd-HH").log"
    $logLine | Out-File -FilePath "$($global:logPath)\$logFileName" -Append -Encoding utf8
 
    # Print Logline
    Write-Host $logLine -ForegroundColor $color
}
 
#Test it
Write-Log "My Message" 
Write-Log "My Warning Message" "WARN"
Write-Log "My Error Message" "ERROR"
Write-Log "My Debug Message" "DEBUG"

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.