Helpers/Write-Log.ps1

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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<#
    .SYNOPSIS
        Log a message with the specified log level.
 
    .DESCRIPTION
        If the specified log level is higher as the configured log level, the
        message will be logged to the enabled destinations. These are the
        specified log file, the PowerShell event log and the current PowerShell
        console.
 
    .INPUTS
        None.
 
    .OUTPUTS
        None.
 
    .EXAMPLE
        PS C:\> Write-Log -Name 'Default' -Message 'My Warning Message' -Level Warning
        Log the warning message.
 
    .NOTES
        Author : Claudio Spizzi
        License : MIT License
 
    .LINK
        https://github.com/claudiospizzi/ScriptLogger
#>


function Write-Log
{
    [CmdletBinding(SupportsShouldProcess = $true)]
    param
    (
        # The logger name.
        [Parameter(Mandatory = $true)]
        [System.String]
        $Name,

        # The message to log.
        [Parameter(Mandatory = $true)]
        [System.String]
        $Message,

        # The log level to use.
        [Parameter(Mandatory = $true)]
        [ValidateSet('Verbose', 'Information', 'Warning', 'Error')]
        [System.String]
        $Level
    )

    if ($Script:Loggers.ContainsKey($Name))
    {
        $logger = $Script:Loggers[$Name]

        # Check if the logging enabled
        if ($logger.Enabled)
        {
            $levelMap = @{
                'Verbose'     = 0
                'Information' = 1
                'Warning'     = 2
                'Error'       = 3
            }

            # Check the logging level: The requested level needs to be equals or higher than the configured level
            if ($levelMap[$Level] -ge $levelMap[$logger.Level])
            {
                if ($logger.LogFile -and $PSCmdlet.ShouldProcess('LogFile', 'Write Log'))
                {
                    try
                    {
                        # Output to log file
                        $line = $logger.Format -f (Get-Date), $env:ComputerName, $Env:Username, $Level, $Message
                        $line | Out-File -FilePath $logger.Path -Encoding $logger.Encoding -Append -ErrorAction Stop
                    }
                    catch
                    {
                        Write-Warning "ScriptLogger '$Name' module error during write log file: $_"
                    }
                }

                if ($logger.EventLog -and $PSCmdlet.ShouldProcess('EventLog', 'Write Log'))
                {
                    $entryType = $Level.Replace('Verbose', 'Information')

                    try
                    {
                        # Output to event log
                        Write-EventLog -LogName 'Windows PowerShell' -Source 'PowerShell' -EventId 0 -Category 0 -EntryType $entryType -Message $Message -ErrorAction Stop
                    }
                    catch
                    {
                        Write-Warning "ScriptLogger '$Name' module error during write event log: $_"
                    }
                }

                if ($logger.ConsoleOutput -and $PSCmdlet.ShouldProcess('ConsoleOutput', 'Write Log'))
                {
                    switch ($Level)
                    {
                        'Verbose'     { Show-VerboseMessage -Message $Message }
                        'Information' { Show-InformationMessage -Message $Message }
                        'Warning'     { Show-WarningMessage -Message $Message }
                        'Error'       { Show-ErrorMessage -Message $Message }
                    }
                }
            }
        }
    }
    else
    {
        Write-Warning "ScriptLogger '$Name' not found. No logs written."
    }
}