Private/Write-Log.ps1
|
<#
.SYNOPSIS Writes a log message .DESCRIPTION Writes a log message to both console and log file .PARAMETER Message The log message .PARAMETER Level Log level (DEBUG, INFO, WARNING, ERROR, AUDIT) .PARAMETER WorkspacePath Optional workspace path for log file location #> function Write-Log { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string]$Message, [Parameter(Mandatory=$false)] [ValidateSet('DEBUG', 'INFO', 'WARNING', 'ERROR', 'AUDIT')] [string]$Level = 'INFO', [string]$WorkspacePath ) try { $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" $logMessage = "[$timestamp] [$Level] $Message" # Write to console with color coding $color = switch ($Level) { 'ERROR' { 'Red' } 'WARNING' { 'Yellow' } 'INFO' { 'White' } 'DEBUG' { 'Gray' } 'AUDIT' { 'Cyan' } default { 'White' } } Write-Host $logMessage -ForegroundColor $color # Write to log file if workspace path is available if ($WorkspacePath) { $logsPath = Join-Path -Path $WorkspacePath -ChildPath "Logs" if (-not (Test-Path -Path $logsPath)) { New-Item -ItemType Directory -Path $logsPath -Force | Out-Null } $logFile = Join-Path -Path $logsPath -ChildPath "NLBaseline_$(Get-Date -Format 'yyyyMMdd').log" Add-Content -Path $logFile -Value $logMessage } } catch { $ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss" Write-Host "[$ts] [ERROR] Failed to write log: $_" -ForegroundColor Red } } |