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
}