Last active
April 24, 2020 18:07
-
-
Save peaeater/93317cf6f08e1d1de1a715f1192cfd8c to your computer and use it in GitHub Desktop.
Log Helper writes to Event Log, console host or file depending on log source.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
Logging functions. | |
#> | |
function logError([string]$logsrc, [string]$msg) { | |
if ([String]::IsNullOrWhiteSpace($logsrc)) { | |
write-log -msg $msg -level "ERROR" | |
} | |
elseif (@(".txt", ".log").Contains([System.IO.Path]::GetExtension($logsrc)) -eq $true) { | |
write-log -msg $msg -level "ERROR" -file $logsrc | |
} | |
else { | |
# write error msg to Application EventLog | |
Write-EventLog -LogName Application -Source $logsrc -EventId 500 -EntryType Error -Message $msg -Category 0 | |
} | |
} | |
function logInfo([string]$logsrc, [string]$msg) { | |
if ([String]::IsNullOrWhiteSpace($logsrc)) { | |
write-log -msg $msg -level "INFO" | |
} | |
elseif (@(".txt", ".log").Contains([System.IO.Path]::GetExtension($logsrc)) -eq $true) { | |
write-log -msg $msg -level "INFO" -file $logsrc | |
} | |
else { | |
# write info msg to Application EventLog | |
Write-EventLog -LogName Application -Source $logsrc -EventId 200 -EntryType Information -Message $msg -Category 0 | |
} | |
} | |
function logWarning([string]$logsrc, [string]$msg) { | |
if ([String]::IsNullOrWhiteSpace($logsrc)) { | |
Write-Host $msg -ForegroundColor Yellow | |
} | |
elseif (@(".txt", ".log").Contains([System.IO.Path]::GetExtension($logsrc)) -eq $true) { | |
write-log -msg $msg -level "WARN" -file $logsrc | |
} | |
else { | |
Write-EventLog -LogName Application -Source $logsrc -EventId 400 -EntryType Warning -Message $msg -Category 0 | |
} | |
} | |
# write log lines to a file | |
function write-log { | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory=$true)] | |
[string]$msg, | |
[Parameter(Mandatory=$false)] | |
[ValidateSet("INFO","WARN","ERROR","DEBUG")] | |
[string]$level = "INFO", | |
[Parameter(Mandatory=$false)] | |
[string]$file | |
) | |
$stamp = (get-date).ToString("yyyy/MM/dd HH:mm:ss") | |
$line = "$stamp $level $msg" | |
if ($file) { | |
add-content $file -Value $line | |
} | |
# always write to console | |
if ($level -eq "ERROR") { | |
write-host $msg -ForegroundColor Red | |
} | |
elseif ($level -eq "WARN") { | |
write-host $msg -ForegroundColor Yellow | |
} | |
else { | |
write-host $msg | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment