1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| function New-Logger {
param( [string]$Name = "Script",
[string]$LogDirectory = "C:\Logs",
[ValidateSet("DEBUG", "INFO", "WARN", "ERROR")] [string]$MinLevel = "INFO",
[switch]$LogToConsole,
[switch]$LogToFile,
[int]$MaxFileSizeMB = 10,
[int]$MaxFiles = 5 )
$logPath = Join-Path $LogDirectory "$Name-$(Get-Date -Format 'yyyyMMdd').log"
return [PSCustomObject]@{ Name = $Name LogPath = $logPath MinLevel = $MinLevel LogToConsole = $LogToConsole LogToFile = $LogToFile MaxFileSizeMB = $MaxFileSizeMB MaxFiles = $MaxFiles } | Add-Member -MemberType ScriptMethod -Name Write -Value { param($Message, $Level = "INFO")
$levelOrder = @{ DEBUG = 0; INFO = 1; WARN = 2; ERROR = 3 } if ($levelOrder[$Level] -lt $levelOrder[$this.MinLevel]) { return }
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff" $entry = "[$timestamp] [$Level] [$($this.Name)] $Message"
if ($this.LogToConsole) { $color = switch ($Level) { "DEBUG" { "DarkGray" } "INFO" { "Cyan" } "WARN" { "Yellow" } "ERROR" { "Red" } } Write-Host $entry -ForegroundColor $color }
if ($this.LogToFile) { if (Test-Path $this.LogPath) { $size = (Get-Item $this.LogPath).Length / 1MB if ($size -ge $this.MaxFileSizeMB) { $baseName = $this.LogPath -replace '\.log$', '' for ($i = $this.MaxFiles - 1; $i -ge 1; $i--) { $old = "$baseName.$i.log" if (Test-Path $old) { if ($i -eq $this.MaxFiles - 1) { Remove-Item $old -Force } else { Move-Item $old "$baseName.$($i+1).log" -Force } } } Move-Item $this.LogPath "$baseName.1.log" -Force } }
$logDir = Split-Path $this.LogPath -Parent if (-not (Test-Path $logDir)) { New-Item $logDir -ItemType Directory -Force | Out-Null } Add-Content -Path $this.LogPath -Value $entry -Encoding UTF8 } } -Force -PassThru }
$log = New-Logger -Name "Deploy" -LogDirectory "C:\Logs\Deploy" ` -LogToConsole -LogToFile -MinLevel DEBUG
$log.Write("部署开始", "INFO") $log.Write("备份旧版本", "DEBUG") $log.Write("停止服务", "INFO") $log.Write("复制文件", "INFO") $log.Write("磁盘空间不足", "WARN") $log.Write("服务启动失败", "ERROR") $log.Write("部署完成", "INFO")
|