-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging_module.ps1
More file actions
120 lines (103 loc) · 3.86 KB
/
logging_module.ps1
File metadata and controls
120 lines (103 loc) · 3.86 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<#
LoggingModule.ps1 - 日誌記錄模組
Version: v1.0
#>
# 全局日誌變量
$global:LogSession = @{
LogFile = $null
SessionStart = Get-Date
SessionId = [guid]::NewGuid().ToString()
}
function Initialize-Logging {
param(
[string]$LogDirectory = "$env:ProgramData\SystemBackupTool\Logs",
[int]$MaxLogFiles = 10
)
# 確保日誌目錄存在
if (-not (Test-Path $LogDirectory)) {
New-Item -Path $LogDirectory -ItemType Directory -Force | Out-Null
}
# 清理舊日誌
Get-ChildItem -Path $LogDirectory -Filter "*.log" |
Sort-Object LastWriteTime -Descending |
Select-Object -Skip $MaxLogFiles |
Remove-Item -Force
# 創建新日誌文件
$logFileName = "SystemBackup_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
$global:LogSession.LogFile = Join-Path $LogDirectory $logFileName
# 寫入日誌頭部
Add-LogEntry -Message "=== 系統備份工具日誌 ===" -Level INFO
Add-LogEntry -Message "會話ID: $($global:LogSession.SessionId)" -Level INFO
Add-LogEntry -Message "開始時間: $($global:LogSession.SessionStart)" -Level INFO
Add-LogEntry -Message "主機名: $env:COMPUTERNAME" -Level INFO
Add-LogEntry -Message "用戶: $env:USERNAME" -Level INFO
Add-LogEntry -Message "PowerShell版本: $($PSVersionTable.PSVersion)" -Level INFO
}
function Add-LogEntry {
param(
[Parameter(Mandatory=$true)]
[string]$Message,
[ValidateSet("DEBUG","INFO","WARNING","ERROR","CRITICAL")]
[string]$Level = "INFO",
[switch]$ConsoleOutput,
[switch]$GUIOutput
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff"
$logEntry = "[$timestamp][$Level] $Message"
# 寫入日誌文件
if ($global:LogSession.LogFile) {
try {
$logEntry | Out-File -FilePath $global:LogSession.LogFile -Append -Encoding UTF8
} catch {
Write-Host "無法寫入日誌文件: $_" -ForegroundColor Red
}
}
# 控制台輸出
if ($ConsoleOutput -or $Level -in ("ERROR","CRITICAL","WARNING")) {
switch ($Level) {
"ERROR" { $color = "Red" }
"CRITICAL" { $color = "DarkRed" }
"WARNING" { $color = "Yellow" }
default { $color = "White" }
}
Write-Host $logEntry -ForegroundColor $color
}
# GUI輸出
if ($GUIOutput -and $global:GUI -and $global:GUI.LogTextBox) {
$global:GUI.LogTextBox.AppendText("$logEntry`r`n")
$global:GUI.LogTextBox.SelectionStart = $global:GUI.LogTextBox.Text.Length
$global:GUI.LogTextBox.ScrollToCaret()
[System.Windows.Forms.Application]::DoEvents()
}
}
function Invoke-WithLogging {
param(
[Parameter(Mandatory=$true)]
[scriptblock]$Command,
[string]$Activity,
[string]$SuccessMessage,
[string]$ErrorMessage,
[switch]$ThrowOnError
)
Add-LogEntry -Message "開始操作: $Activity" -Level INFO -ConsoleOutput -GUIOutput
try {
$result = & $Command
Add-LogEntry -Message $SuccessMessage -Level INFO -ConsoleOutput -GUIOutput
return $result
} catch {
$errorMsg = if ($ErrorMessage) { $ErrorMessage } else { "操作失敗: $_" }
Add-LogEntry -Message $errorMsg -Level ERROR -ConsoleOutput -GUIOutput
Add-LogEntry -Message "錯誤詳細資訊: $($_.Exception | Format-List -Force | Out-String)" -Level DEBUG
if ($ThrowOnError) {
throw
}
return $null
}
}
function Complete-Logging {
$duration = (Get-Date) - $global:LogSession.SessionStart
Add-LogEntry -Message "會話完成, 持續時間: $($duration.ToString('hh\:mm\:ss'))" -Level INFO
Add-LogEntry -Message "=== 日誌結束 ===" -Level INFO
}
# 匯出函數
Export-ModuleMember -Function Initialize-Logging, Add-LogEntry, Invoke-WithLogging, Complete-Logging