'Building functional logs

Good Afternoon,

So I recently have been shifting my focus to developing more enterprise grade PowerShell scripts and using them across multiple domains and as such issues will happen no matter how many fringe cases you try to imagine and plan for. As such to aid in the troubleshooting of the inevitable problems you need to build logging into the scripts. I have been struggling back and forth of what is the best way to actually build multi-level logging functionality without the script being basically one giant blob of write-this, write-that etc. I am trying to strike a balance between code quantity, code readability, and just amount of development time it takes to tackle the problem.

TLDR; Implementing good logging is hard.

  • What decision process do you follow when deciding what to log and what level it should be?
  • What are some tips or lessons learned when building more complex tools?

What I have currently settled on (or more like what am I teetering between). I also use $ErrorActionPreference = Stop and a trap function to pretty up the errors.

Method 1

Write-Debug "Attempting to load BdeHdCfg."
Try { $lMSG = 'Loading BDEHDCFG state: {0}'
    Set-Variable -Name:'BdeHdCfg' -Value:(Start-BdeHdCfg)
    Write-Information ($lMSG -f 'Success')
} Catch {
    Write-Error ($lMSG -f 'Failure')
}

Method 2

Write-Debug "Attempting to load TPM information."
Try { $lMSG = 'Successfully loaded TPM information: {0}'
    Set-Variable -Name:'TPM' -Value:(Get-TargetTPM)
} Finally {
    Write-Information ($lMSG -f ( -Not [String]::IsNullOrWhiteSpace($TPM)))
}


Solution 1:[1]

Your best bet for enterprise grade PowerShell logging is to use code written and maintained by those who know powershell better than we do.

My de facto method for logging is to use the aptly named Logging module, they have great documentation.

It is an actively maintained and mature solution for logging and below is a very basic excerpt for implementing it in your own scripts.

Set-LoggingDefaultLevel -Level 'WARNING'
Add-LoggingTarget -Name Console
Add-LoggingTarget -Name File -Configuration @{Path = 'C:\Temp\example_%{+%Y%m%d}.log'}

Write-Log -Level 'INFO' -Message 'Some really useful logging message'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Otter