Private/Write-SqlSpnEventLog.ps1

# =============================================================================
# Script : Write-SqlSpnEventLog.ps1
# Author : Keith Ramsey
# =============================================================================
# Change Log
# -----------------------------------------------------------------------------
# 2026-05-09 Keith Ramsey Phase 2 release polish - DR-202 standard header applied.
# =============================================================================
function Write-SqlSpnEventLog {
    <#
    .SYNOPSIS
        Best-effort write to the Windows Application Event Log under source 'SqlSpnManager'.
    .DESCRIPTION
        Registers the source on first call if missing and the current process is elevated;
        otherwise silently skips for the rest of the session. Event ID conventions:
            INFO -> 1000 (Information)
            SUCCESS -> 1001 (SuccessAudit)
            WARN -> 2000 (Warning)
            ERROR -> 3000 (Error)
        Per BTRD TR-202; complements the per-invocation file log written by Write-SqlSpnLog.
    .NOTES
        Failures here never propagate. The file log is the authoritative audit record;
        Event Log emission is the SIEM-readiness convenience.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)][string]$Message,
        [ValidateSet('INFO','WARN','ERROR','SUCCESS')][string]$Level = 'INFO'
    )

    if ($script:SqlSpnEventLogDisabled) { return }

    $source = 'SqlSpnManager'
    $logName = 'Application'

    try {
        $exists = [System.Diagnostics.EventLog]::SourceExists($source)
    }
    catch {
        $script:SqlSpnEventLogDisabled = $true
        return
    }

    if (-not $exists) {
        try {
            [System.Diagnostics.EventLog]::CreateEventSource($source, $logName)
        }
        catch {
            $script:SqlSpnEventLogDisabled = $true
            return
        }
    }

    $entryType = switch ($Level) {
        'INFO'    { [System.Diagnostics.EventLogEntryType]::Information }
        'SUCCESS' { [System.Diagnostics.EventLogEntryType]::SuccessAudit }
        'WARN'    { [System.Diagnostics.EventLogEntryType]::Warning }
        'ERROR'   { [System.Diagnostics.EventLogEntryType]::Error }
    }

    $eventId = switch ($Level) {
        'INFO'    { 1000 }
        'SUCCESS' { 1001 }
        'WARN'    { 2000 }
        'ERROR'   { 3000 }
    }

    try {
        [System.Diagnostics.EventLog]::WriteEntry($source, $Message, $entryType, $eventId)
    }
    catch {
        $script:SqlSpnEventLogDisabled = $true
    }
}