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("デバッグログ");