# Logging.ps1 — shared logging utility # Requires $InternalRoot to be defined in the calling script's scope before dot-sourcing. function Write-Log { [CmdletBinding()] param( [ValidateSet('Info', 'Warn', 'Error')] [string]$Level = 'Info', [Parameter(Mandatory)] [string]$Message, [string]$Feature = 'General' ) $logDir = Join-Path $InternalRoot 'data\logs' if (-not (Test-Path $logDir)) { New-Item -ItemType Directory -Path $logDir -Force | Out-Null } $logFile = Join-Path $logDir "automation-$(Get-Date -Format 'yyyy-MM-dd').log" $timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss' $levelPad = $Level.ToUpper().PadRight(5) $line = "[$timestamp] [$levelPad] [$Feature] $Message" try { Add-Content -Path $logFile -Value $line -Encoding UTF8 -ErrorAction Stop } catch { # Logging must never crash the caller — silently ignore write failures } # Rotate: remove logs older than 7 days Get-ChildItem -Path $logDir -Filter 'automation-*.log' -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } | Remove-Item -Force -ErrorAction SilentlyContinue }