handlers/file.psm1
$DEFAULT_LOG_FOLDER = "$($env:SystemRoot)\Logs" function New-uLogFile { param( [string] $Name, [string] $Source = $MyInvocation.ScriptName, [string] $Formatter = [LogFormatter]::FileDefault, [LogLevel] $Level = [LogLevel]::SUCCESS, [string] $Path = '', [switch] $Append, [Switch] $Enabled ) Begin{ if ($Path -eq ''){ $guid = [guid]::NewGuid().guid if ($Source -eq ''){ $Source = 'Console' $Path = "$DEFAULT_LOG_FOLDER\PowerShellConsole.log" }else{ $Path = "$DEFAULT_LOG_FOLDER\$((Get-Item $Source).Name).log" try{ 'test' | Out-File -LiteralPath "$Path$guid" -ErrorAction Stop Remove-Item "$Path$guid" -Force }catch{ try{ $Path = "$Source.log" 'test' | Out-File -LiteralPath "$Path$guid" -ErrorAction Stop Remove-Item "$Path$guid" -Force }catch{ $Path = "$($env:TEMP)\$((Get-Item $Source).Name).log" } } } } } Process{ try{ # try/cath usefull if the script is run from a soft that doesn't support consoel interface Write-Host "log in : '$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} $Record | Add-Member -MemberType NoteProperty Source -Value $this.Source $FormattedMessage = & $this.Formatter -Record $Record if ($Record.Level -ge $this.Level){ $FormattedMessage | Out-File -LiteralPath $this.Path -Encoding utf8 -Append } } $log } } |