LLI Wiki — My Digital Knowledge Base

PowerShell logger with levels and log rotation

PowerShell Write-Log function with severity levels, colored output and size-based log file rotation.

This PowerShell script provides a Write-Log function with severity levels (DEBUG, INFO, WARN, ERROR, FATAL), colored console output, file logging and automatic size-based log rotation.

Parameters

Parameter Purpose Default
$logFile Log file name app_<computer name>.log
$logLevel Minimum level that is logged DEBUG
$logSize Maximum size before rotation 10mb
$logCount Maximum number of files kept 5

A message whose level is below $logLevel is skipped. An invalid level is still written to the log together with an error line.

Code (logger.ps1)

# all logging settings are here on top
param(
    [Parameter(Mandatory=$false)]
        [string]$logFile = "app_$(gc env:computername).log",
    [Parameter(Mandatory=$false)]
        [string]$logLevel = "DEBUG", # ("DEBUG","INFO","WARN","ERROR","FATAL")
    [Parameter(Mandatory=$false)]
        [int64]$logSize = 10mb,
    [Parameter(Mandatory=$false)]
        [int]$logCount = 5
)
# end of settings

function Write-Log-Line ($line, $logFile) {
    $logFile | %{
           If (Test-Path -Path $_) { Get-Item $_ }
           Else { New-Item -Path $_ -Force }
    } | Add-Content -Value $Line -erroraction SilentlyContinue
}

function Roll-logFile
{
    # checks whether the file is larger than the specified size; if so it rolls the log
    # and deletes the oldest logs when there are more than x logs.
    param(
        [string]$fileName = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")+".log",
        [int64]$maxSize = $logSize,
        [int]$maxCount = $logCount
    )
    $logRollStatus = $true
    if(test-path $filename) {
        $file = Get-ChildItem $filename
        # Start the log-roll if the file is big enough
        if($file.length -ge $maxSize) {
            Write-Log-Line "$Stamp INFO Log file size $('{0:N0}' -f $file.length) is larger than max size $('{0:N0}' -f $maxSize). Rolling log file!" $logFile
            $fileDir = $file.Directory
            $fbase = $file.BaseName
            $fext = $file.Extension
            $fn = $file.name #this gets the name of the file we started with

            function refresh-log-files {
                 Get-ChildItem $filedir | ?{ $_.Extension -match "$fext" -and $_.name -like "$fbase*"} | Sort-Object lastwritetime
            }
            function fileByIndex($index) {
                $fileByIndex = $files | ?{($_.Name).split("-")[-1].trim("$fext") -eq $($index | % tostring 00)}
                $fileByIndex
            }
            function getNumberOfFile($theFile) {
                $NumberOfFile = $theFile.Name.split("-")[-1].trim("$fext")
                if ($NumberOfFile -match '[a-z]'){
                    $NumberOfFile = "01"
                }
                $NumberOfFile
            }

            refresh-log-files | %{
                [int32]$num = getNumberOfFile $_
                Write-Log-Line "LOGGER: checking log file number $num" $logFile
                if ([int32]$($num | % tostring 00) -ge $maxCount) {
                    write-host "LOGGER: files above log max count $maxCount : $_"
                    Write-Log-Line "LOGGER: Deleting files above log max count $maxCount : $_" $logFile
                    Remove-Item $_.fullName
                }
            }

            $files = @(refresh-log-files)

            # Now there should be at most $maxCount files, and the highest number is one less than count, unless there are badly named files, eg non-numbers
            for ($i = $files.count; $i -gt 0; $i--) {
                $newfilename = "$fbase-$($i | % tostring 00)$fext"
                if($i -gt 1) {
                    $fileToMove = fileByIndex($i-1)
                } else {
                    $fileToMove = $file
                }
                if (Test-Path $fileToMove.PSPath) { # If there are holes in sequence, file by index might not exist. The 'hole' will shift to next number, as files below hole are moved to fill it
                    write-host "LOGGER: '$fileToMove' => '$newfilename'"
                    # $fileToMove is a System.IO.FileInfo, but $newfilename is a string. Move-Item takes a string, so we need full path
                    Move-Item ($fileToMove.FullName) -Destination $fileDir\$newfilename -Force
                }
            }
        } else {
            $logRollStatus = $false
        }
    } else {
        $logrollStatus = $false
    }
    $LogRollStatus
}


Function Write-Log {
    [CmdletBinding()]
    Param(
    [Parameter(Mandatory=$True)]
    [string]
    $Message,

    [Parameter(Mandatory=$False)]
    [String]
    $Level = "INFO"
    ,

    [Parameter(Mandatory=$False)]
    [String]
    $logFile = "app_$(gc env:computername).log"
    )

    $levels = ("DEBUG","INFO","WARN","ERROR","FATAL")
    $logLevelPos = [array]::IndexOf($levels, $logLevel)
    $levelPos = [array]::IndexOf($levels, $Level)
    $Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss:fff")

    # First roll the log if needed to null to avoid output
    $Null = @(
        Roll-logFile -fileName $logFile -filesize $logSize -logcount $logCount
    )

    if ($logLevelPos -lt 0){
        Write-Log-Line "$Stamp ERROR Wrong logLevel configuration [$logLevel]" $logFile
    }

    if ($levelPos -lt 0){
        Write-Log-Line "$Stamp ERROR Wrong log level parameter [$Level]" $logFile
    }

    # if level parameter is wrong or configuration is wrong I still want to see the
    # message in log
    if ($levelPos -lt $logLevelPos -and $levelPos -ge 0 -and $logLevelPos -ge 0){
        return
    }

    $Line = "$Stamp $Level $Message"

    $fc = $host.UI.RawUI.ForegroundColor
    switch ($Level) {
     "INFO"   {$host.UI.RawUI.ForegroundColor = "Green" ;break;}
     "WARN"   {$host.UI.RawUI.ForegroundColor = "Yellow" ;break;}
     "ERROR"  {$host.UI.RawUI.ForegroundColor = "Red";break;}
     "FATAL"  {$host.UI.RawUI.ForegroundColor = "Red";break;}
     "DEBUG"  {"";break;}
    }
    Write-Output $Line
    $host.UI.RawUI.ForegroundColor = $fc
    Write-Log-Line $Line $logFile
}

Test

. .\logger.ps1

Write-Log "Started" "INFO"

for ($i = 100; $i -gt 0; $i--)
{
    Write-Log "debug message"
    Write-Log "debug message2" "DEBUG"
    Write-Log "info message" "INFO"
    Write-Log "warn message" "WARN"
    Write-Log "error message" "ERROR"
    Write-Log "fatal message" "FATAL"
    Write-Log "message with wrong level" "WRONG"
}
Mastodon LLIMastodon SocialFosstodon