Skip to content

Instantly share code, notes, and snippets.

@ninmonkey
Created August 11, 2023 18:19
Show Gist options
  • Save ninmonkey/269934261ddd96ac62a0920b7d9ed4ea to your computer and use it in GitHub Desktop.
Save ninmonkey/269934261ddd96ac62a0920b7d9ed4ea to your computer and use it in GitHub Desktop.
Write-LogMessage.ps1.md
Write-LogMessage Verbose -Message 'stuff' -Json @{ 'user' = 'bob'; id = 100 }
function New-SafeFileTimeNowString {
    <#
    .SYNOPSIS
        timenow for safe filepaths: "2022-08-17_12-46-47Z"
    .notes
        distinct values to the level of a full second
    #>
    [CmdletBinding()]
    param() 
    (Get-Date).ToString('u') -replace '\s+', '_' -replace ':', '-'
}
$script:NewLogPath = Join-Path 'g:\temp\logs' ('{0}.log' -f @(New-SafeFileTimeNowString))
function Write-LogMessage {
    param(
        [Parameter(mandatory, Position=0)]
        [ValidateSet('Warning', 'Error', 'Verbose')]                
        [string]$Severity, [string]$Message, [string]$Details,
        [switch]$AsVerbose,        
        [Alias('Json')][object]$Payload, [switch]$PassThru
        [string]$TimeFormat = 'u'
    )
    $when = [datetime]::Now.ToString($TimeFormat)
    $render = $when, $severity, $Message, $details -join ': ' 
    $renderJson = $payload 
        | ConvertTo-Json -Depth 2 -Compress -ea 'ignore' -wa 'ignore'

    $render = $render, $renderJson -join '; '
    if($AsVerbose) { $Render | Write-Verbose  }
    if($AsWarning) { $Render | Write-Warning  }
    if($AsHost) { $Render | write-host -back 'darkblue' }
    $render
        | Add-Content -Path $Script:NewLogPath -PassThru:$PassThru
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment