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      = "$DEFAULT_LOG_FOLDER\$((Get-Item $Source).Name).log",
    [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)\$($Source).log"
            'test' | Out-File -LiteralPath $Path -ErrorAction Stop
            Remove-Item $Path -Force
        }catch{                
            $Path = "$($env:TEMP)\$($logName).log"
        }
    }    
    
    try{
        Write-Host "log path : '$Path'"
    }catch{}

    $log = [PSCustomObject] @{Name      = $Name;
                              Enabled   = $Enabled;
                              Type      = 'file';
                              Formatter = $Formatter;
                              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
        
        $FormattedMessage | Out-File -LiteralPath $this.Path -Encoding unicode -Append
    
    }

    $log
}
}