Skip to content

Instantly share code, notes, and snippets.

@peaeater
Created January 9, 2025 18:24
Show Gist options
  • Save peaeater/b692e9a129988ac385774d12ab35a8c5 to your computer and use it in GitHub Desktop.
Save peaeater/b692e9a129988ac385774d12ab35a8c5 to your computer and use it in GitHub Desktop.
Checks one or more timestamped logs for errors and sends email notification via postmark. Windows and Linux. Requires helper.logging.ps1.
#!/usr/bin/pwsh
<#
Check one or more logs for errors and notify.
Needs helper.logging.ps1
#>
param(
[string[]]$in,
[datetime]$since = (get-date).AddDays(-1),
[string]$logsrc = "",
[switch]$donotnotify,
[string[]]$to = @("EMAIL1","EMAIL2"),
[string]$from = "FROM",
[string]$token = "POSTMARK TOKEN",
[string]$curl = "curl"
)
<#
FUNCTIONS
#>
. (join-path $PSScriptRoot helper.logging.ps1) -LogSource $logsrc -ErrorsToWinLogSource $null
function parseDate([string]$string) {
$date_parsed = get-date
# very simple parse because log timestamps should be culture invariant
if ([datetime]::TryParse($string, [ref]$date_parsed)) {
return $date_parsed
}
else {
return $null
}
}
<#
ERROR HANDLING
#>
trap {
logError -msg "$($_.ScriptStackTrace) $($error[0])"
exit 1
}
<#
MAIN
#>
$machine = [System.Environment]::MachineName
$report_lines = @()
$error_count = 0
# for each log file, get filename and any errors found
foreach ($logfile in $in) {
$errors = get-content -path $logfile | where-object {
$_ -match "^(?<timestamp>.+)\sERROR" `
-and (parseDate -string $Matches.timestamp) -gt $since
}
if ($errors.Length -gt 0) {
$error_count += $errors.Length
$report_lines += "`n`n$machine $logfile"
$report_lines += $errors
}
}
$report_subject = "$error_count errors found on $([System.Environment]::MachineName) since $since"
logInfo -msg $report_subject
# notify
if ($donotnotify -eq $false -and $error_count -gt 0) {
$report_data = @{
From = $from
To = $to -join ","
Subject = $report_subject
MessageStream = "outbound"
TextBody = $report_lines -join "`n"
}
$report_json = $report_data | ConvertTo-Json -Compress
logInfo -msg $report_json
$response = & $curl "https://api.postmarkapp.com/email" `
-X POST `
-H "Accept: application/json" `
-H "Content-Type: application/json" `
-H "X-Postmark-Server-Token: $token" `
-d $($report_data | ConvertTo-Json -Compress)
logInfo -msg $response
}
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment