Functions/Out-DryLog.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
<#
.SYNOPSIS
A logging and output-to-display module for DryDeploy
 
.DESCRIPTION
A logging and output-to-display module for DryDeploy
 
.PARAMETER Type
Types follow Windows Streams, except for stream 1 (output) which isn't
used. You may also use first letter of a stream name, so type 2 and 'e'
are both the error stream, type 3 and 'w' the warning, and so on.
    Type 2 or 'e' = Error
    Type 3 or 'w' = Warning
    Type 4 or 'v' = Verbose
    Type 5 or 'd' = Debug
    Type 6 or 'i' = Information
 
.PARAMETER Message
The text to display and/or log.
 
.PARAMETER MsgHash
A hashtable to display and/or log
 
.PARAMETER MsgArr
A two-element array; for instance a hashtable key and it's corresponding value.
Out-DryLog will add whitespaces to the first element until it reaches a length
of `$LoggingOptions.array_first_element_length, which orders all second elements
in a straight vertical line. So basically for readability of a pair
 
.PARAMETER Header
Creates a line that seperates previous stuff from upcoming stuff, and then
displays the meader message, like:
..........................................................................
This is a normal header
 
.PARAMETER SmallHeader
Displays the header message, and then fills rest of the line with the header
chars, like
 
This is a small header ..................................................
 
.PARAMETER Air
'Airs' the message in header or smallheader, converts 'Air' to 'A i r', like
..........................................................................
A i r e d H e a d e r
 
.PARAMETER Callstacklevel
This function uses Get-PSCallstack to identify the location of the caller, i.e.
which function or script, and at what line, Out-DryLog was called. For certain
types (see parameter Type above) the function will then display that location on
the far right of each displayed line. You may configure for which types the
calling location should be displayed in `$LoggingOptions. Anyway, if a function
or many functions call the same proxy function that in turn calls Out-DryLog, it
may be more informative if the proxy function calls Out-DryLog with '-Callstacklevel 2'.
The effect is that the Location is no longer the PS Callstack element number 1 (the
proxy function), but element number 2 (the function that called the proxy function)
 
.EXAMPLE
Out-DryLog -Type 6 -Message "This is a type 6 (informational) message"
 
                              This is a type 6 (informational) message
.EXAMPLE
Out-DryLog 6 "This is a type 6 (informational) message"
                              This is a type 6 (informational) message
 
.EXAMPLE
ol 6 "This is a type 6 (informational) message"
                              This is a type 6 (informational) message
 
.EXAMPLE
$GLOBAL:GlobalResourceName = "DC001-S1-D"
$GLOBAL:GlobalActionName = "ProvisionDsc"
ol 6 "This is a type 6 (informational) message"
         [DC001-S1-D]: [ProvisionDsc] This is a type 6 (informational) message
 
.EXAMPLE
ol 4 "This is a type 4 (verbose) message which won't display anything"
 
 
.EXAMPLE
ol 4 "This is a type 4 (verbose) message" -Verbose
VERBOSE: [DC001-S1-D]: [ProvisionDsc] This is a type 4 (verbose) message [MyScript.ps1:245 14:25:57]
 
.EXAMPLE
ol i 'This is an','arrayed message' ; ol i 'And this is','another one'
         [DC001-S1-D]: This is an : arrayed message
         [DC001-S1-D]: And this is : another one
#>

Function Out-DryLog {
    [CmdletBinding(DefaultParameterSetName="message")]
    [Alias("ol")]
    Param (
        [Alias("t")]
        [Parameter(Position=0)]
        [String]$Type,

        [Alias("m")]
        [Parameter(ParameterSetName="message",Mandatory,Position=1)]
        [AllowEmptyString()]
        [String]$Message,

        [Alias("hash")]
        [Parameter(ParameterSetName="hashtable",Mandatory,Position=1)]
        [hashtable]$MsgHash,

        [Alias("arr")]
        [Parameter(ParameterSetName="array",Mandatory,Position=1,
        HelpMessage="The 'array' parameter set expects an array of 2 elements, for instance a name or description of a
        value of some kind, and the second element is the value. Out-DryLog will add whitespaces to the first element
        until it reaches a length of `$LoggingOptions.array_first_element_length, which orders all second elements in
        a straight vertical line. So basically for readability of a pair"
)]
        [ValidateScript({"$_.Count -eq 2"})]
        [Array]$MsgArr,

        [Alias("h")]
        [Parameter(ParameterSetName="message",HelpMessage="Creates a nice header of the message text")]
        [Switch]$Header,

        [Alias("sh")]
        [Parameter(ParameterSetName="message",HelpMessage="Creates a nice, small header of the message text")]
        [Switch]$SmallHeader,

        [Alias("a")]
        [Parameter(ParameterSetName="message",HelpMessage="If -Header or -SmallHeader, converts 'Message' to 'M e s s a g e'")]
        [Switch]$Air,

        [Alias("cs")]
        [Parameter(HelpMessage="Normally 1, the direct caller. However, if Out-DryLog is called by a proxy function, you may use
        2 to point the 'location' (where in your code Out-DryLog was called) to the call before the direct call."
)]
        [Int]$Callstacklevel = 1
    )


    # Default type is 4 (verbose) for message, 5 (debug) for hashtables and arrays
    If ($Null -eq $Type) {
        Switch ($PSCmdlet.ParameterSetName) {
            'message'   { $Type = 4 }
            'array'     { $Type = 5 }
            'hashtable' { $Type = 5 }
        }
    }

    Try {

        # In the DryDeploy framework, $LoggingOptions is defined in the global scope. If not defined, the locally defined options are used
        If ($Null -eq $GLOBAL:LoggingOptions) {
            $DefaultLogFilePath = ("$($ENV:LOCALAPPDATA)\Dry\DryLog.log").Replace('\','\\')
            $DefaultLoggingOptionsString = @"
            {
                "log_to_file": true,
                "path": "$DefaultLogFilePath",
                "left_column_width": 30,
                "console_width_threshold": 70,
                "post_buffer": 3,
                "array_first_element_length": 45,
                "verbose": {
                    "foreground_color": "Cyan",
                    "display_location": true
                },
                "debug": {
                    "foreground_color": "DarkCyan",
                    "display_location": true
                },
                "warning": {
                    "foreground_color": "Yellow",
                    "display_location": true
                },
                "information": {
                    "foreground_color": "White",
                    "display_location": false
                },
                "error": {
                    "foreground_color": "Red",
                    "display_location": true
                }
            }
"@

            $LoggingOptions = $DefaultLoggingOptionsString |
            ConvertFrom-Json -ErrorAction Stop
        }
        Else {
            $LoggingOptions = $GLOBAL:LoggingOptions
        }

        # Define path to logfile
        If ($LoggingOptions.log_to_file -eq $True) {
            If ($LoggingOptions.path) {
                $LogFile = $LoggingOptions.path
            }
            ElseIf ($LoggingOptions.path_expression) {
                $LogFile = Invoke-Expression -Command $LoggingOptions.path_expression -ErrorAction Stop
            }
            Else {
                Throw "You must define LoggingOptions.path or LoggingOptions.path_expression to log to file"
            }
        }
        Else {
            $LogFile = $Null
        }

        # Check that $LogFile is defined, turn off logging to file if not
        If (($Null -eq $LogFile) -or ($LogFile -eq "")) {
            # Only warn once, don't nag all the time
            If ($GLOBAL:DoNotLogToFile -ne $True) {
                Write-Warning -Message "`$LogFile is undefined -> logging to file is disabled. Define LoggingOptions.path or .path_expression to enable it!" -WarningAction Continue
                [Bool]$GLOBAL:DoNotLogToFile = $True
            }
        }
        Else {
            # Make sure $LogFile exist if $GLOBAL:DoNotLogToFile -ne $True
            If (($GLOBAL:DoNotLogToFile -ne $True) -and (-not (Test-Path $LogFile))) {
                New-Item -ItemType File -Path $LogFile -Force -ErrorAction Stop | Out-Null
            }
        }

        # Get the calling cmdlet/script and line number
        $Caller = (Get-PSCallStack)[$callstacklevel]
        [String] $Location = ($Caller.location).Replace(' line ','')
        [String] $LocationString = "[$Location $(get-date -Format HH:mm:ss)]"

        $DisplayLogMessage = $False
        <#
            Windows Output Streams:
            1 OutPut/Success - not in use here
            2 Error
            3 Warning (was 1)
            4 Verbose (was 0)
            5 Debug (was 3)
            6 Information
        #>


        Switch ($Type) {
            {$_ -in ('2','e')} {
                $TextType = "ERROR: "
                $LOFore = $LoggingOptions.error.foreground_color
                $LOBack = $LoggingOptions.error.background_color
                $DisplayLocation = $LoggingOptions.error.display_location
                $DisplayLogMessage = $True

            }
            {$_ -in ('3','w')} {
                $TextType = "WARNING:"
                $LOFore = $LoggingOptions.warning.foreground_color
                $LOBack = $LoggingOptions.warning.background_color
                $DisplayLocation = $LoggingOptions.warning.display_location
                $DisplayLogMessage = $True
            }
            {$_ -in ('5','d')} {
                $TextType = "DEBUG: "
                $LOFore = $LoggingOptions.debug.foreground_color
                $LOBack = $LoggingOptions.debug.background_color
                $DisplayLocation = $LoggingOptions.debug.display_location
                If ($PSBoundParameters.ContainsKey('Debug') -or ($PSCmdlet.GetVariableValue('DebugPreference') -eq 'Continue')) {
                    $DisplayLogMessage = $True
                }
            }
            {$_ -in ('6','i')} {
                $TextType = " "
                $LOFore = $LoggingOptions.information.foreground_color
                $LOBack = $LoggingOptions.information.background_color
                $DisplayLocation = $LoggingOptions.information.display_location
                $DisplayLogMessage = $True
            }
            's' {
                $TextType = " "
                $StatusText = 'Success'
                $LOFore = 'green'
                $DisplayLogMessage = $GLOBAL:ShowStatus
                $DisplayLocation = $False
            }
            'f' {
                $TextType = " "
                $StatusText = 'Fail'
                $LOFore = 'red'
                $DisplayLogMessage = $GLOBAL:ShowStatus
                $DisplayLocation = $False
            }
            Default {
                $Type = 'v'
                $TextType = "VERBOSE:"
                $LOFore = $LoggingOptions.verbose.foreground_color
                $LOBack = $LoggingOptions.verbose.background_color
                $DisplayLocation = $LoggingOptions.verbose.display_location
                If ($PSBoundParameters.ContainsKey('Verbose') -or ($PSCmdlet.GetVariableValue('VerbosePreference') -eq 'Continue')) {
                    $DisplayLogMessage = $True
                }
            }
        }

        If (($Null -ne $LOFore) -or ($Null -ne $LOBack)) {
            [hashtable]$LogColors = @{}
            If ($Null -ne $LOFore) {
                $LogColors+=@{'foregroundcolor'="$LOFore"}
            }
            If ($Null -ne $LOBack) {
                $LogColors+=@{'backgroundcolor'="$LOBack"}
            }
        }

        # Break if we're not displaying message anyway
        If ($DisplayLogMessage) {

            # Create start of message
            If (($Null -ne $GLOBAL:GlobalResourceName) -and ($GLOBAL:GlobalResourceName -ne '')){
                $StartOfMessage = $TextType + ' [' + $GLOBAL:GlobalResourceName + ']:'
            }
            Else {
                $StartOfMessage = $TextType
            }

            # make sure left_column is a certain length
            While ($StartOfMessage.length -lt $LoggingOptions.left_column_width) {
                $StartOfMessage = $StartOfMessage + ' '
            }

            If (($Null -ne $GLOBAL:GlobalActionName) -and ($GLOBAL:GlobalActionName -ne '')){
                If ($Null -ne $GLOBAL:GlobalPhase) {
                $StartOfMessage += '[' + $GLOBAL:GlobalActionName + '][' +  $GLOBAL:GlobalPhase  +'] '
                }
                Else {
                    $StartOfMessage += '[' + $GLOBAL:GlobalActionName + '] '
                }
            }

            If ($DisplayLocation) {
                $TargetMessageLength = $Host.UI.RawUI.WindowSize.Width - ($LoggingOptions.post_buffer + $StartOfMessage.Length + $LocationString.Length)
            }
            Else {
                $TargetMessageLength = $Host.UI.RawUI.WindowSize.Width - ($LoggingOptions.post_buffer + $StartOfMessage.Length)
            }

            If ($Header) {
                # Get-DryHeader will call Out-DryLog back after making a header
                $HeaderLine,$Message = Get-DryHeader -Message $Message -TargetMessageLength $TargetMessageLength -Air:$Air
            }
            ElseIf ($SmallHeader) {
                $Message = Get-DryHeader -Message $Message -Small -TargetMessageLength $TargetMessageLength -Air:$Air
            }

            If ($PSCmdlet.ParameterSetName -eq 'message') {
                If ($Type -in @('s','f')) {
                    Do {
                        $StatusText = "$StatusText "
                    }
                    While($StatusText.length -le $LoggingOptions.array_first_element_length)
                    $Messages = @("$StatusText`: $Message")
                }
                # If $TargetMessageLength is greater than the $LoggingOptions.console_width_threshold, and
                # $Message is longer than $TargetMessageLength, we want to split the message
                # into chunks so they fit nicely in the console
                ElseIf (
                    ($TargetMessageLength -gt $LoggingOptions.console_width_threshold) -and
                    ($Message.Length -gt $TargetMessageLength)
                ) {
                    [Array]$Messages = Split-DryString -Length $TargetMessageLength -String $Message
                }
                Else {
                    If ($HeaderLine) {
                        [Array]$Messages += $HeaderLine
                    }
                    [Array]$Messages += $Message
                }
            }
            ElseIf ($PSCmdlet.ParameterSetName -eq 'hashtable') {
                # hashtable - loop through all key-value pairs
                $Messages = @("Hashtable:")
                Foreach ($Key in $MsgHash.Keys) {
                    Remove-Variable -Name ThisValue -ErrorAction Ignore
                    If ($($MsgHash[$Key]) -is [PSCredential]) {
                        If ($GLOBAL:ShowPasswords) {
                            $ThisValue = ($MsgHash[$Key]).UserName + '===>' + ($MsgHash[$Key]).GetNetworkCredential().Password
                        }
                        Else {
                            $ThisValue = ($MsgHash[$Key]).UserName
                        }
                    }
                    Else {
                        If ($Key -match "password") {
                            Do {
                                $ThisValue = "$ThisValue*"
                            }
                            Until ($ThisValue.Length -ge ($MsgHash[$Key]).Length)
                        }
                        Else {
                            $ThisValue = $MsgHash[$Key]
                        }
                    }
                    $Messages += "'$Key" + '=' + $ThisValue + "'"
                }
            }
            ElseIf ($PSCmdlet.ParameterSetName -eq 'array') {
                $FirstElement = $MsgArr[0]
                $SecondElement = $MsgArr[1]

                Do {
                    $FirstElement = "$FirstElement "
                }
                While($FirstElement.length -le $LoggingOptions.array_first_element_length)
                $Messages = @("$($FirstElement): $($SecondElement)")
            }

            Foreach ($MessageChunk in $Messages) {
                Do {
                    $MessageChunk = "$MessageChunk "
                }
                While($MessageChunk.length -le $TargetMessageLength)

                # Attach the pieces
                If ($DisplayLocation) {
                    $FullMessageChunk = $StartOfMessage + $MessageChunk + $LocationString
                }
                Else {
                    $FullMessageChunk = $StartOfMessage + $MessageChunk
                }

                If ($LogColors) {
                    Write-Host @LogColors -Object $FullMessageChunk
                }
                Else {
                    Write-Host -Object $FullMessageChunk
                }
            }
        }

        # Log to file
        Switch ($LoggingOptions.log_to_file) {
            $True {
                Switch ($PSCmdlet.ParameterSetName) {
                    'message' {
                        If (-not $Header) {
                            $LogMessage = "{0} `$$<{1}><{2} {3}><thread={4}>" -f ($StartOfMessage + ": " + $Message), $Location, (Get-Date -Format "MM-dd-yyyy"), (Get-Date -Format "HH:mm:ss.ffffff"), $PID
                            $LogMessage | Out-File -Append -Encoding UTF8 -FilePath ("filesystem::{0}" -f $LogFile) -Force
                        }
                    }
                    'hashtable' {
                        Foreach ($Key in $MsgHash.Keys) {
                            $LogMessage = "{0} `$$<{1}><{2} {3}><thread={4}>" -f ($StartOfMessage + ": " + $Key + '=' + $MsgHash[$Key] ), $Location, (Get-Date -Format "MM-dd-yyyy"), (Get-Date -Format "HH:mm:ss.ffffff"), $PID
                            $LogMessage | Out-File -Append -Encoding UTF8 -FilePath ("filesystem::{0}" -f $LogFile) -Force
                        }
                    }
                    'array' {
                        $LogMessage = "{0} `$$<{1}><{2} {3}><thread={4}>" -f ($StartOfMessage + ": " + $MsgArr[0] + ' => ' + $MsgArr[1] ), $Location, (Get-Date -Format "MM-dd-yyyy"), (Get-Date -Format "HH:mm:ss.ffffff"), $PID
                        $LogMessage | Out-File -Append -Encoding UTF8 -FilePath ("filesystem::{0}" -f $LogFile) -Force
                    }
                }
            }
            Default {
                # do nothing
            }
        }
    }
    Catch {
        $PSCmdlet.ThrowTerminatingError($_)
    }
}