0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

powershellで使う Logger class

Last updated at Posted at 2023-09-28

powershellで使うログクラスの記録

class Logger {
    #-------------------------------------------------------------------------------------
    # [仕様]
    # ・ログファイルは、日付で保持する。
    # ・ログファイルは、指定ファイル数保持する。超えた場合、超えた分は削除する。
    # ・ログフォーマット:yyyy/MM/dd HH:mm:SS [log-type] [message]
    #-------------------------------------------------------------------------------------

    # variable
    [string] $log_file_dir;
    [string] $log_file_name;
    [string] $log_file_path;
    [int]    $log_file_keep_count;


    # constructor
    Logger([string]$path){
        $this.log_file_dir        = $path;
        $this.log_file_name       = "Log_" + (Get-Date).ToString("yyyyMMdd") + ".log";
        $this.log_file_path       = $this.log_file_dir + "/" + $this.log_file_name;
        $this.log_file_keep_count = 14;
        $this.OldestLogFileRemove();

    }
    Logger([string]$path, [int]$keep_count){
        $this.log_file_dir        = $path;
        $this.log_file_name       = "Log_" + (Get-Date).ToString("yyyyMMdd") + ".log";
        $this.log_file_path       = $this.log_file_dir + "/" + $this.log_file_name;
        $this.log_file_keep_count = $keep_count;
        $this.OldestLogFileRemove();
    }

    
    # method
    [void] OldestLogFileRemove(){
        $file_count = (Get-ChildItem $this.log_file_dir -File).Count;
        if ( $file_count -gt $this.log_file_keep_count ) {
            $oldestFile = Get-ChildItem $this.log_file_dir  | Sort-Object LastWriteTime | Select-Object -First 1;
            Remove-Item $oldestFile.FullName -Force;
            $this.Info("Remove: " +  $oldestFile.FullName);
        }
    }

    [int] WriteLog([string]$log_type,[string]$content){ 
        $text = (Get-Date).ToString("yyyy/MM/dd HH:mm:ss") + " [" + $log_type + "] " + $content;
        # 書き出し
        Write-Output $text | Out-File -FilePath $this.log_file_path -Encoding utf8 -Append;
        return 0;
    }
    [void] Info([string]$message) {
        $this.WriteLog("Info ", $message);
    }
    [void] Error([string]$message) { 
        $this.WriteLog("Error", $message);
    }
    [void] Debug([string]$message) { 
        $this.WriteLog("Debug", $message);
    }

}


$log = New-Object Logger("D:\PowerShell-Script\TEST-FOLDER\LOG");

$log.Info("情報ログ");
$log.Error("エラーログ");
$log.Debug("デバッグログ");
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?