-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWrite-Log.psm1
More file actions
82 lines (65 loc) · 2.44 KB
/
Copy pathWrite-Log.psm1
File metadata and controls
82 lines (65 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#Requires -Version 7.0
<#
.SYNOPSIS
Structured, timestamped logging for scripts in this repository.
.DESCRIPTION
Provides a single Write-Log command that writes a timestamped, level-tagged
line to the appropriate PowerShell stream. Import it from a script with:
Import-Module "$PSScriptRoot/Write-Log.psm1" -Force
This is a module (.psm1), not a script: importing it actually defines the
Write-Log command, unlike importing a plain .ps1.
.NOTES
Author: Sebastian Gräf
Repo: https://github.com/segraef/Scripts
#>
function Write-Log {
<#
.SYNOPSIS
Write a timestamped, level-tagged log line.
.PARAMETER Message
The text to log. Accepts pipeline input.
.PARAMETER Level
Severity: Info (default), Warning, Error, or Verbose. Selects the stream.
.PARAMETER ErrorRecord
An ErrorRecord to append (message + collapsed stack trace). Forces Error level.
.EXAMPLE
Write-Log 'Starting deployment.'
.EXAMPLE
try { ... } catch { Write-Log -Message 'Deployment failed.' -ErrorRecord $_ }
#>
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSAvoidUsingWriteHost', '',
Justification = 'Info-level output is intended for the interactive console.')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSAvoidOverwritingBuiltInCmdlets', '',
Justification = 'Write-Log is this repository deliberate logging helper, not the obscure built-in.')]
param
(
[Parameter(Mandatory, Position = 0, ValueFromPipeline)]
[ValidateNotNull()]
[string]$Message,
[Parameter()]
[ValidateSet('Info', 'Warning', 'Error', 'Verbose')]
[string]$Level = 'Info',
[Parameter()]
[System.Management.Automation.ErrorRecord]$ErrorRecord
)
process {
$timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
$line = "[$timestamp] $Message"
if ($ErrorRecord) {
$traceText = "$($ErrorRecord.ScriptStackTrace)"
$trace = ($traceText -split "`n" | Where-Object { $_ }) -join ' <- '
Write-Error -Message "$line | $($ErrorRecord.Exception.Message) | $trace"
return
}
switch ($Level) {
'Warning' { Write-Warning $line }
'Error' { Write-Error $line }
'Verbose' { Write-Verbose $line }
default { Write-Host $line }
}
}
}
Export-ModuleMember -Function Write-Log