handlers/file.psm1


$DEFAULT_LOG_FOLDER = "$($env:SystemRoot)\Logs"

function New-uLogFile
{
param(
    [string] $Name,
    [string] $Source    = $MyInvocation.ScriptName,
    [string] $Formatter = [LogFormatter]::FileDefault,
    [string] $Level,
    [string] $Path      = '',
    [switch] $Append,
    [Switch] $Enabled   = $true
)
Begin{
    if ($Path -eq ''){
        if ($Source -eq ''){
            $Source = 'Console'
            $Path   = "$DEFAULT_LOG_FOLDER\PowerShellConsole.log"
        }else{
            
            $Path   = "$DEFAULT_LOG_FOLDER\$((Get-Item $Source).Name).log"
        }
    }
}
Process{
    
    try{
        'test' | Out-File -LiteralPath $Path -ErrorAction Stop
        Remove-Item $Path -Force
    }catch{
        try{
            $Path = "$([System.Environment]::CurrentDirectory)\$((Get-Item $Source).Name).log"
            'test' | Out-File -LiteralPath $Path -ErrorAction Stop
            Remove-Item $Path -Force
        }catch{                
            $Path = "$($env:TEMP)\$((Get-Item $Source).Name).log"
        }
    }    
    
    try{
        Write-Host "log path : '$Path'"
    }catch{}

    $log = [PSCustomObject] @{Name      = $Name;
                              Enabled   = $Enabled;
                              Type      = 'file';
                              Formatter = $Formatter;
                              Level     = $Level;
                              Source    = $Source;
                              Path      = $Path
                             }

    $log | Add-Member -MemberType ScriptMethod -Name WriteLog -Value {
        param($Record)

        if (-not $this.Enabled){return}

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

        $FormattedMessage = & $this.Formatter -Record $Record
        
        if ($this.Level -le $Record.Level){
            $FormattedMessage | Out-File -LiteralPath $this.Path -Encoding unicode -Append
        }
    
    }

    $log
}
}