Logging & Monitoring
Structured Logging with PowerShell¶
Enterprise scripts require consistent, machine-readable logging to enable centralized monitoring and troubleshooting. PowerShell provides built-in cmdlets like Write-EventLog for writing to Windows Event Logs, which is a system destination. Structured logging refers to the format (e.g., JSON or CSV) used to represent log data, not the destination. For structured logging, implement custom functions to generate formatted entries. Use the Level parameter to categorize events (Verbose, Warning, Error, etc.) and include timestamps, source, and contextual data.
Example: Structured Log Entry¶
function Log-Message {
param (
[string]$Message,
[string]$Level = 'Information',
[string]$LogFilePath = "$env:TEMP\script.log",
[string]$EventLogName = 'Application',
[string]$EventLogSource = 'MyScript'
)
$timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
$logEntry = @{
Timestamp = $timestamp
Level = $Level
Message = $Message
Source = $EventLogSource
ScriptName = $MyInvocation.MyCommand.Name
LineNumber = $MyInvocation.ScriptLineNumber
}
$jsonLog = $logEntry | ConvertTo-Json
Write-Output $jsonLog
$json,Log | Out-File -FilePath $LogFilePath -Append
Write-EventLog -LogName $EventLogName -Source $EventLogSource -EventId 1001 -Message $jsonLog
}
# Example usage
Log-Message -Message "Failed to connect to server" -Level Error
Best Practices¶
- Use JSON or CSV formats for machine-parsable logs.
- Include script name, function name, and line numbers in log entries.
- Store logs in a centralized location (e.g., UNC path) for audit trails.
- Avoid conflating structured logging formats with Windows Event Log destinations.
Event Tracing with Transcripts¶
PowerShell’s Start-Transcript and Stop-Transcript cmdlets capture real-time script execution, including commands, errors, and output. This is ideal for debugging and post-mortem analysis.
Example: Script Execution Transcript¶
Start-Transcript -Path "C:\Logs\ScriptTranscript_$(Get-Date -Format 'yyyyMMddHHmm').log" -IncludeInvocationHeader
try {
# Simulate a script
Get-Service | Where-Object { $_.Status -eq 'Stopped' }
} catch {
Log-Message -Message "Script failed: $_" -Level Error
} finally {
Stop-Transcript
}
Tips¶
- Use
-IncludeInvocationHeaderto capture command-line context. - Combine with structured logging for dual logging (transcript + formatted logs).
Writing to Windows Event Logs¶
Windows Event Logs provide a centralized repository for system and application events. PowerShell scripts can write to these logs using Write-EventLog and query them using Get-WinEvent.
Example: Writing to Event Log¶
Write-EventLog -LogName Application -Source "MyScript" -EventId 1001 -Message "Script completed successfully"
Example: Querying Event Logs¶
Monitoring Tools¶
- Event Viewer: Use for real-time monitoring.
- PowerShell: Automate log analysis with
Get-WinEventand filtering. - Third-party tools: Integrate with Splunk, ELK Stack, or Azure Monitor for centralized logging.
Key takeaways¶
- Use structured logging formats (JSON/CSV) for centralized monitoring.
- Leverage
Start-Transcriptfor detailed script execution tracking. - Write to Windows Event Logs for system-wide visibility and compliance.
- Combine structured logging with real-time monitoring tools for proactive issue detection.
- Always include contextual data (timestamp, source, severity) in log entries.