Private/Initialize-Logger.ps1
|
function Initialize-Logger { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [object]$Config ) $scriptRootPath = $Config.ScriptRootPath $vSphereEnvironment = $Config.EnvironmentConfig.Name $logsFolder = Join-Path -Path $scriptRootPath -ChildPath (Join-Path -Path "Logs" -ChildPath $vSphereEnvironment) # StrictMode-safe access (config.Logging and nested properties might not exist) $logLevel = 'INFO' $rotateAfterAmount = 7 $loggingProp = $Config.PSObject.Properties['Logging'] if ($null -ne $loggingProp -and $null -ne $loggingProp.Value) { $logging = $loggingProp.Value $llProp = $logging.PSObject.Properties['LogLevel'] if ($null -ne $llProp -and -not [string]::IsNullOrWhiteSpace([string]$llProp.Value)) { $logLevel = [string]$llProp.Value } $lrProp = $logging.PSObject.Properties['LogRetentionDays'] if ($null -ne $lrProp -and -not [string]::IsNullOrWhiteSpace([string]$lrProp.Value)) { $tmp = 0 if ([int]::TryParse([string]$lrProp.Value, [ref]$tmp) -and $tmp -gt 0) { $rotateAfterAmount = $tmp } } } $logFormat = "[%{timestamp:+yyyy-MM-dd HH:mm:ss.fffffzzz}][%{level:-7}][%{lineno:3}] %{message}" $logFileName = Join-Path -Path $logsFolder -ChildPath "vSphereConnector-%{+yyyyMMdd}.log" $zipFileName = Join-Path -Path $logsFolder -ChildPath "RotatedLogs.zip" if (-not (Test-Path -Path $logsFolder)) { New-Item -Path $logsFolder -ItemType Directory -Force | Out-Null } Set-LoggingDefaultLevel -Level $logLevel Set-LoggingCallerScope 2 Add-LoggingTarget -Name File -Configuration @{ Path = $logFileName Encoding = 'unicode' Level = $logLevel Format = $logFormat RotateAfterAmount = $rotateAfterAmount RotateAmount = 1 CompressionPath = $zipFileName } } |