Private/Write-WULog.ps1

function Write-WULog {
    <#
    .SYNOPSIS
        Centralized logging function for WindowsUpdateTools module.
 
    .DESCRIPTION
        Provides consistent logging across all WindowsUpdateTools functions with
        timestamp formatting, severity levels, and both console and file output.
 
    .PARAMETER Message
        The message to log.
 
    .PARAMETER Level
        Severity level of the message. Valid values: Info, Warning, Error, Verbose
 
    .PARAMETER LogPath
        Path to the log file. If not specified, writes only to console.
 
    .PARAMETER NoConsole
        Suppress console output - write only to log file.
 
    .EXAMPLE
        Write-WULog -Message "Starting Windows Update analysis" -LogPath "C:\Logs\wu.log"
 
    .EXAMPLE
        Write-WULog -Message "Service not running" -Level Warning -LogPath $LogPath
 
    .NOTES
        This is a private function used internally by the WindowsUpdateTools module.
    #>


    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$Message,

        [ValidateSet('Info', 'Warning', 'Error', 'Verbose')]
        [string]$Level = 'Info',

        [string]$LogPath,

        [switch]$NoConsole
    )    # Generate timestamp
    $timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
    
    # Format log entry
    $logEntry = "[$timestamp] [$Level] $Message"    # Write to console (unless suppressed)
    if (-not $NoConsole) {
        switch ($Level) {
            'Error' { 
                Write-Host "ERROR: $Message" -ForegroundColor Red
            }
            'Warning' { 
                Write-Host "WARNING: $Message" -ForegroundColor Yellow
            }
            'Verbose' { 
                Write-Verbose $Message
            }
            'Info' { 
                Write-Information $logEntry -InformationAction Continue
            }
        }
    }

    # Write to log file (if path provided)
    if ($LogPath) {
        try {
            # Ensure directory exists
            $logDirectory = Split-Path $LogPath -Parent
            if ($logDirectory -and -not (Test-Path $logDirectory)) {
                New-Item -Path $logDirectory -ItemType Directory -Force | Out-Null
            }

            # Append to log file
            Add-Content -Path $LogPath -Value $logEntry -ErrorAction Stop
        }
        catch {
            # If logging fails, at least try to show the error on console
            Write-Warning "Failed to write to log file '$LogPath': $($_.Exception.Message)"
            Write-Warning "Original message was: $Message"
        }
    }
}