handlers/eventlog.psm1


function New-uLogEventLog
{
param(
    [string] $Name      = '',
    [string] $Source    = $MyInvocation.ScriptName,
    [string] $Formatter = [LogFormatter]::EventlogDefault,
    [string] $Level,
    [string] $LogName   = 'Application',
    [Switch] $Enabled   = $true
)
Begin{
    if ($Source -eq ''){$Source = 'Console'}
}
Process{
    
    if ($Source -like '*\*'){ 
        $EventSource = (Get-Item $Source).BaseName 
    }else{
        $EventSource = $Source
    }
    
    try{
        New-EventLog -LogName Application -Source $EventSource -ErrorAction Stop
    }catch{
        switch ($_.FullyQualifiedErrorId){
            'AccessIsDenied,Microsoft.PowerShell.Commands.NewEventLogCommand' {
                # script launched as user,so he does not have the privilege to create a new source
                # using PowerShell as source
                $EventSource = 'PowerShell'
                $LogName     = 'Windows PowerShell'
            }
        }
    }

    $log = [PSCustomObject] @{Name         = $Name;;
                              Enabled      = $Enabled;
                              Type         = 'eventlog';
                              Formatter    = $Formatter;
                              Source       = $Source;
                              LogName      = $LogName;
                              EventSource  = $EventSource
                              EventlogName = $LogName                              
                             }
     
    $log | Add-Member -MemberType ScriptMethod -Name WriteLog -Value {
        param($Record)

        if (-not $this.Enabled){return}
        
        switch($Record.Level){
            ([LogLevel]::WARNING)     {$EventLevel = 'Warning';break}
            ([LogLevel]::WARN)        {$EventLevel = 'Warning';break}
            ([LogLevel]::ERROR)       {$EventLevel = 'Error';break}
            ([LogLevel]::CRITICAL)    {$EventLevel = 'Error';break}
            ([LogLevel]::FATAL)       {$EventLevel = 'Error';break}
            default                   {$EventLevel = 'Information'}
        }        

        if ($this.EventSource -eq 'PowerShell'){
            $Record.Id += 1000
        }

        if ($this.Formatter -notmatch '-'){$this.Formatter = 'Format-' + $this.Formatter}

        $FormattedMessage = & $this.Formatter -Record $Record

        $eventMessage = "Source : $($this.Source) `n$FormattedMessage" 

        Write-EventLog -LogName $this.LogName `
                       -EventId $Record.Id `
                       -EntryType $EventLevel `
                       -Source $this.EventSource `
                       -Message $eventMessage 
    
    }

    $log
}
}