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
  }

  Write ([string]$logMessage) {
    # default CFLoggerErrorLevel is INFO
    [CFLoggerErrorLevel]$errorLevel="INFO"
    $this.Write($logMessage,$errorLevel,$null)
  }

  Write ([string]$logMessage, [CFLoggerErrorLevel]$errorLevel) {
    $this.Write($logMessage,$errorLevel,$null)
  }

  Write ([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"
        }
      }
    }
  }
}