Skip to content

Instantly share code, notes, and snippets.

@praveenc
Created April 6, 2018 03:52
Show Gist options
  • Save praveenc/cc245363f95b3583c2171e119ae46283 to your computer and use it in GitHub Desktop.
Save praveenc/cc245363f95b3583c2171e119ae46283 to your computer and use it in GitHub Desktop.
Powershell Logger Class - log output in Log4net format
class Logger {
[string] $LogFileName = "env-init-log"
[string] $LogFilePath
# Constructor
Logger() {
$dtstart = (Get-Date -Format "yyyyMMddhhmmss").ToString()
$currdir = (Resolve-Path .).Path
$ScriptName = Join-Path "$currdir" -ChildPath "$($this.LogFileName)"
$this.LogFilePath = "{0}_{1}" -f $ScriptName, $dtstart
}
# Constructor with FilePath
Logger ([string] $FilePath) {
$parentFolder = Split-Path "$FilePath"
# Ensure path is valid; Validate path using Resolve Path
if (Test-Path "$parentFolder") {
$this.LogFileName = Split-Path "$FilePath" -Leaf
$this.LogFilePath = $FilePath
}
else {
Throw "Path not found: $parentFolder"
}
}
[void] Info([string]$Message) {
$this.writeLogLine('INFO', $Message)
}
[void] Warn([string]$Message) {
$this.writeLogLine('WARN', $Message)
}
[void] Debug([string]$Message) {
$this.writeLogLine('DEBUG', $Message)
}
[void] Error([string]$Message) {
$this.writeLogLine('ERROR', $Message)
}
[void] writeLogLine([String]$lineType, [String]$LogMessage) {
$dt = (Get-Date -Format "yyyy-MM-dd hh:mm:ss").ToString()
$logline = "[$dt] [$lineType] $LogMessage"
$logline | Out-File -FilePath "$($this.LogFilePath)" -Append -Encoding default -NoClobber
}
}
[Logger] $Logger = [Logger]::new()
$Logger.Info("Logger Initialized")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment