Private/Helpers/Write-PSMBLog.ps1
|
function Write-PSMBLog { <# .SYNOPSIS Writes a timestamped entry to the PSModuleBrowser debug log. .DESCRIPTION Cross-platform file logger. Disabled by default - set the environment variable PSMB_DEBUG=1 to enable. Log location defaults to <TempDir>/PSModuleBrowser/PSModuleBrowser.log but can be overridden with PSMB_LOG_DIR. #> param( [Parameter(Mandatory)] [string]$Message, [ValidateSet('DEBUG', 'INFO', 'WARN', 'ERROR')] [string]$Level = 'INFO' ) if (-not $script:PSMBLogEnabled) { return } $logDir = if ($env:PSMB_LOG_DIR) { $env:PSMB_LOG_DIR } else { [System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), 'PSModuleBrowser') } if (-not [System.IO.Directory]::Exists($logDir)) { try { [System.IO.Directory]::CreateDirectory($logDir) | Out-Null } catch { return } } $logFile = [System.IO.Path]::Combine($logDir, 'PSModuleBrowser.log') $timestamp = [datetime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ss.fffZ') $entry = "$timestamp [$Level] (PID:$PID) $Message" try { $stream = [System.IO.File]::Open( $logFile, [System.IO.FileMode]::Append, [System.IO.FileAccess]::Write, [System.IO.FileShare]::ReadWrite ) $writer = [System.IO.StreamWriter]::new($stream) $writer.WriteLine($entry) $writer.Dispose() $stream.Dispose() } catch { } } |