Functions/Out-DryLog.ps1

<#
.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($_)
    }
}