LoginSignup
3
4

More than 5 years have passed since last update.

PowerShell 自作LoggerClass

Last updated at Posted at 2018-09-05

■概要

・自身の仕事で使用するために作成したロガークラスです。
・インスタンス化して使用します。
・出力対象(ファイル、コンソール)が設定できます。
・出力レベル(Info、Warn、Error、Debug)が設定できます。
・マルチスレッドに対応しております。(MUTEX)
・外部ファイルは使用しておりません。

以下の記事を参考にして作成しました。
https://qiita.com/miyamiya/items/f36ce9c4b0ffea26afe0

■環境

PSVersion:5.1

■ロガークラス

MyLogger.psm1
#ログ処理
class MyLogger {

    #ログファイルのパス パスを設定しない場合はログを出力しない
    [string] $LogPath = ""

    #true Write-Hostする,False Write-Hostしない
    [bool] $ShouldWriteHost = $true

    #エンコーディング
    [string] $Encoding = "Default"

    #各ログレベルの使用可否 true:可 
    [bool] $IsInfoEnabled  = $true
    [bool] $IsWarnEnabled  = $true
    [bool] $IsErrorEnabled = $true
    [bool] $IsDebugEnabled = $true    

    #MUTEX名 空白の場合ログファイル名
    [string] $MutexName = ""

    MyLogger () {        
    }

    MyLogger ([string]$logPath, [bool]$shouldWriteHost) {
        $this.LogPath         = $logPath
        $this.ShouldWriteHost = $shouldWriteHost
    }

    #Info出力
    [void] Info($msg) {
        if ($this.IsInfoEnabled) {
            $this.PutLog("INFO", $msg) 
        }
    }
    #Warn出力
    [void] Warn($msg) {
        if ($this.IsWarnEnabled) {
            $this.PutLog("WARN", $msg) 
        }
    }  
    #Error出力
    [void] Error($msg) {
        if ($this.IsErrorEnabled) {
            $this.PutLog("ERROR", $msg) 
        }
    }   
    #Debug出力
    [void] Debug($msg) {
        if ($this.IsDebugEnabled) {
            $this.PutLog("DEBUG", $msg) 
        }
    } 

    #ログ出力
    hidden [void] PutLog([string]$level, [string]$msg) {

        $logparam = $null                     #WriteHost文字色, 出力ログレベル文字列 
        if ($level -eq "INFO")  { $logparam = @("White",    "INFO") }
        if ($level -eq "WARN")  { $logparam = @("Yellow",   "WARN") }
        if ($level -eq "ERROR") { $logparam = @("Red",      "ERROR") }
        if ($level -eq "DEBUG") { $logparam = @("DarkGray", "DEBUG") }

        $logtxt = "[$(Get-Date -Format "yyyy/MM/dd HH:mm:ss")] {0} {1}" -f $logparam[1].PadRight(5), $msg

        #画面表示
        if($this.ShouldWriteHost) {
            Write-Host -ForegroundColor $logparam[0] $logtxt
        }

        #ログ出力 パスがない場合はログを出力しない
        if($this.LogPath) {
            $mutex = New-Object System.Threading.Mutex($false, $this.GetMutexName())
            $mutex.WaitOne()
            try {
                Write-Output $logtxt | Out-File -FilePath $this.LogPath -Append -Encoding $this.Encoding
            }
            finally {
                $mutex.ReleaseMutex()
            }
        }
    }

    #Mutex名取得 Mutexプロパティに設定がなければLogファイル名をMutex名にする
    hidden [string] GetMutexName() {
        if ($this.MutexName) {
            return $this.MutexName
        }
        return [System.IO.Path]::GetFileNameWithoutExtension($this.LogPath) 
    }
}

■使用方法

Main.ps1
using module ".\MyLogger.psm1"

$logger = MyLogger::new("C\test.log", $true)
$logger.IsDebugEnabled = $false #DEBUGは出力しない
$logger.Info("情報")
$logger.Debug("デバッグ")
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4