Couple of Logs Analyzing Function

Heya all – here are a couple of quick functions to help analyze logs files. Coming from a ConfigMgr/SCCM background, I got used to reading a LOT of logs. Having a couple of functions like this would have greatly helped!

First – let’s see if there are warning and/or error messages in a log (or stack of logs)

function Analyze-LogContent {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [string]$LogFilePath,

        [string]$ErrorPattern = 'ERROR|Error|error',
        [string]$WarningPattern = 'WARNING|Warning|warning'
    )

    if (-not (Test-Path -Path $LogFilePath)) {
        Write-Error "Log file does not exist at the path: $LogFilePath"
        return
    }

    # Reading the log file
    $logContent = Get-Content -Path $LogFilePath

    # Analyzing for errors
    $errors = $logContent | Where-Object { $_ -match $ErrorPattern }
    $warnings = $logContent | Where-Object { $_ -match $WarningPattern }

    # Output analysis
    $output = @()
    if ($errors.Count -gt 0) {
        $output += "Found $($errors.Count) errors in the log."
    } else {
        $output += "No errors found in the log."
    }

    if ($warnings.Count -gt 0) {
        $output += "Found $($warnings.Count) warnings in the log."
    } else {
        $output += "No warnings found in the log."
    }

    return $output
}

# Example usage
$logPath = "C:\Path\To\Your\LogFile.log"
$result = Analyze-LogContent -LogFilePath $logPath
$result | ForEach-Object { Write-Host $_ }

Change the patterns as necessary – ERR, for example.

The second function is pretty straight forward – summarize a log counting the number of INFO, Warning, and Error messages:

function Summarize-LogFile {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [string]$LogFilePath
    )

    if (-not (Test-Path -Path $LogFilePath)) {
        Write-Error "Log file does not exist at the path: $LogFilePath"
        return
    }

    $logContent = Get-Content -Path $LogFilePath

    $infoCount = 0
    $errorCount = 0
    $warningCount = 0

    foreach ($line in $logContent) {
        switch -Regex ($line) {
            "INFO" { $infoCount++ }
            "ERROR" { $errorCount++ }
            "WARNING" { $warningCount++ }
        }
    }

    $summary = @"
Log File Summary:
Info Entries: $infoCount
Error Entries: $errorCount
Warning Entries: $warningCount
Total Entries: $($logContent.Count)
"@

    return $summary
}

# Example usage
$logPath = "C:\Path\To\Your\LogFile.log"
$summary = Summarize-LogFile -LogFilePath $logPath
Write-Host $summary

There ya go! I will keep adding to these, and eventually get them in Github so you all can tell me how wrong they are 🙂

Happy Coding!

Creating Alert Rules in Azure with AZ PowerShell – Some Samples

Let go over a simple one – how to create various types of alert rules in Azure using the AZ PowerShell Module.

Each example targets a different aspect of Azure monitoring, but doesn’t cover them all. Remember to tweak the parameters to match your environment.

Metric Alerts for Performance Monitoring

To keep an eye on Azure service metrics:

$criteria = New-AzMetricAlertRuleV2Criteria -MetricName 'Percentage CPU' -TimeAggregation Average -Operator GreaterThan -Threshold 80

Add-AzMetricAlertRuleV2 -Name 'HighCPUAlert' -ResourceGroupName 'YourResourceGroupName' -WindowSize 00:05:00 -Frequency 00:01:00 -TargetResourceId '/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/Microsoft.Compute/virtualMachines/yourVMName' -Condition $criteria -ActionGroup '/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/microsoft.insights/actionGroups/yourActionGroupName' -Severity 3 -Description 'Alert on high CPU usage.'

Log Alerts for Custom Log Queries

For alerts based on log analytics:

$query = "AzureActivity | where OperationName == 'Create or Update Virtual Machine' and ActivityStatus == 'Succeeded'"

Set-AzScheduledQueryRule -ResourceGroupName 'YourResourceGroupName' -Location 'East US' -ActionGroup '/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/microsoft.insights/actionGroups/yourActionGroupName' -ConditionQuery $query -Description "VM creation alert" -Enabled $true -EvaluationFrequency 'PT5M' -Severity 0 -WindowSize 'PT5M' -Name 'VMCreationAlert'

Activity Log Alerts for Azure Resource Events

To monitor specific Azure service events:

$condition = New-AzActivityLogAlertCondition -Field 'category' -Equal 'Administrative'
$actionGroupId = "/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/microsoft.insights/actionGroups/yourActionGroupName"

Set-AzActivityLogAlert -Location 'Global' -Name 'AdminActivityAlert' -ResourceGroupName 'YourResourceGroupName' -Scopes "/subscriptions/yourSubscriptionId" -Condition $condition -ActionGroupId $actionGroupId -Description "Alert on administrative activities"

Application Insights Alerts for Application Performance

Track application performance with a simple AppInsights web test

$rule = New-AzApplicationInsightsWebTestAlertRule -Name 'AppPerfAlert' -ResourceGroupName 'YourResourceGroupName' -Location 'East US' -WebTestId '/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/microsoft.insights/webtests/yourWebTestId' -FailedLocationCount 3 -WindowSize 'PT5M' -Frequency 'PT1M' -Criteria $criteria

Set-AzApplicationInsightsWebTestAlertRule -InputObject $rule