CFLogger.psm1
Enum CFLoggerErrorLevel { FATAL = 0 ERROR = 1 WARN = 2 INFO = 3 DEBUG = 4 TRACE = 5 } class CFLogger{ [CFLoggerErrorLevel]$MinErrorLevel = "TRACE" [string]$LogFilePath CFLogger () {} CFLogger ([CFLoggerErrorLevel]$MinErrorLevel, [string]$LogFilePath) { $this.minErrorLevel = $MinErrorLevel $this.logFilePath = $LogFilePath } Log ([string]$logMessage) { # default CFLoggerErrorLevel is INFO [CFLoggerErrorLevel]$errorLevel="INFO" $this.Log($logMessage,$errorLevel,$null) } Log ([string]$logMessage, [CFLoggerErrorLevel]$errorLevel) { $this.Log($logMessage,$errorLevel,$null) } Log ([string]$logMessage, [CFLoggerErrorLevel]$errorLevel, [string]$stack) { $CFLoggerColorTable = @{ OFF = "Black" FATAL = "Red" ERROR = "Magenta" WARN = "Yellow" INFO = "Green" DEBUG = "Cyan" TRACE = "Gray" } $maxErrorLevelLength = ([System.Enum]::GetNames('CFLoggerErrorLevel') | Measure-Object -Maximum -Property Length).Maximum $timeStamp = Get-Date -Format yyyy-MM-ddTHH:mm:ss.fffZ if ($errorLevel.value__ -le $this.minErrorLevel.value__) { # Build output string $writeString = [string]::Format("{0} :: {1} :: {2} {3}", $timeStamp, $errorLevel.ToString().PadRight($maxErrorLevelLength), $logMessage, $stack) # Write to Console Write-Host $writeString -ForegroundColor $CFLoggerColorTable["$errorLevel"] # Write to Log File if ($null -ne $this.logFilePath) { # We have a log file path, so try to write to log file Try { Add-Content -ErrorAction Stop $this.logFilePath $writeString } Catch { $errorWriteString = [string]::Format("{0} :: {1} :: {2}", $timeStamp, "ERROR".PadRight($maxErrorLevelLength), ("Cannot write to specified CFLogger Path: " + $this.logFilePath)) Write-Host $errorWriteString -ForegroundColor "Red" } } } } LogTrace ([string]$logMessage) { $this.Log($logMessage,"TRACE",$null) } LogTrace ([string]$logMessage, [string]$stack) { $this.Log($logMessage,"TRACE",$stack) } LogDebug ([string]$logMessage) { $this.Log($logMessage,"DEBUG",$null) } LogDebug ([string]$logMessage, [string]$stack) { $this.Log($logMessage,"DEBUG",$stack) } LogInfo ([string]$logMessage) { $this.Log($logMessage,"INFO",$null) } LogInfo ([string]$logMessage, [string]$stack) { $this.Log($logMessage,"INFO",$stack) } LogWarn ([string]$logMessage) { $this.Log($logMessage,"WARN",$null) } LogWarn ([string]$logMessage, [string]$stack) { $this.Log($logMessage,"WARN",$stack) } LogError ([string]$logMessage) { $this.Log($logMessage,"ERROR",$null) } LogError ([string]$logMessage, [string]$stack) { $this.Log($logMessage,"ERROR",$stack) } LogFatal ([string]$logMessage) { $this.Log($logMessage,"FATAL",$null) } LogFatal ([string]$logMessage, [string]$stack) { $this.Log($logMessage,"FATAL",$stack) } } function Initialize-CFLogger() { return [CFLogger]::new() } function Initialize-CFLogger([CFLoggerErrorLevel]$minErrorLevel, [string]$logFilePath) { return [CFLogger]::new($minErrorLevel,$logFilePath) } Export-ModuleMember -Function Initialize-CFLogger |