-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathErrorLogger.pas
More file actions
263 lines (211 loc) · 6.14 KB
/
ErrorLogger.pas
File metadata and controls
263 lines (211 loc) · 6.14 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
unit ErrorLogger;
interface
uses
System.SysUtils, System.Classes, System.DateUtils, System.IOUtils,
Vcl.Dialogs, Vcl.Forms;
type
TLogLevel = (llDebug, llInfo, llWarning, llError, llFatal);
TErrorLogger = class
private
class var FInstance: TErrorLogger;
FLogFile: string;
FLogStream: TStreamWriter;
FIsInitialized: Boolean;
FShowDialogs: Boolean;
constructor Create;
destructor Destroy; override;
procedure InitializeLogger;
procedure EnsureLogDirectoryExists;
function GetLogLevelString(Level: TLogLevel): string;
procedure WriteToLog(const Msg: string);
public
class function GetInstance: TErrorLogger;
class procedure ReleaseInstance;
procedure Initialize(const LogFile: string = '');
procedure Log(const Msg: string; Level: TLogLevel = llInfo); overload;
procedure Log(const Msg: string; E: Exception; Level: TLogLevel = llError); overload;
procedure LogFormat(const Fmt: string; const Args: array of const; Level: TLogLevel = llInfo);
procedure ShowErrorDialog(const Msg: string; E: Exception = nil);
procedure ShowWarningDialog(const Msg: string);
procedure ShowInfoDialog(const Msg: string);
property ShowDialogs: Boolean read FShowDialogs write FShowDialogs;
end;
// 全局访问函数
function Logger: TErrorLogger;
// 全局异常处理
procedure InstallGlobalExceptionHandler;
procedure UninstallGlobalExceptionHandler;
implementation
var
PreviousExceptionHandler: TExceptionEvent;
function Logger: TErrorLogger;
begin
Result := TErrorLogger.GetInstance;
end;
procedure GlobalExceptionHandler(Sender: TObject; E: Exception);
begin
Logger.Log('未捕获的异常', E, llFatal);
Logger.ShowErrorDialog('应用程序发生未捕获的异常', E);
// 调用之前的异常处理器(如果有)
if Assigned(PreviousExceptionHandler) then
PreviousExceptionHandler(Sender, E);
end;
procedure InstallGlobalExceptionHandler;
begin
PreviousExceptionHandler := Application.OnException;
Application.OnException := GlobalExceptionHandler;
end;
procedure UninstallGlobalExceptionHandler;
begin
Application.OnException := PreviousExceptionHandler;
end;
{ TErrorLogger }
constructor TErrorLogger.Create;
begin
FIsInitialized := False;
FShowDialogs := True;
end;
destructor TErrorLogger.Destroy;
begin
if Assigned(FLogStream) then
begin
FLogStream.Flush;
FLogStream.Free;
end;
inherited;
end;
procedure TErrorLogger.EnsureLogDirectoryExists;
var
LogDir: string;
begin
LogDir := ExtractFilePath(FLogFile);
if (LogDir <> '') and not DirectoryExists(LogDir) then
ForceDirectories(LogDir);
end;
class function TErrorLogger.GetInstance: TErrorLogger;
begin
if not Assigned(FInstance) then
FInstance := TErrorLogger.Create;
Result := FInstance;
end;
function TErrorLogger.GetLogLevelString(Level: TLogLevel): string;
begin
case Level of
llDebug: Result := 'DEBUG';
llInfo: Result := 'INFO';
llWarning: Result := 'WARNING';
llError: Result := 'ERROR';
llFatal: Result := 'FATAL';
else
Result := 'UNKNOWN';
end;
end;
procedure TErrorLogger.Initialize(const LogFile: string);
begin
if LogFile <> '' then
FLogFile := LogFile
else
FLogFile := ChangeFileExt(ParamStr(0), '.log');
InitializeLogger;
end;
procedure TErrorLogger.InitializeLogger;
begin
if FIsInitialized then Exit;
try
EnsureLogDirectoryExists;
// 创建或追加到日志文件
FLogStream := TStreamWriter.Create(FLogFile, True, TEncoding.UTF8);
FLogStream.AutoFlush := True;
// 写入日志头
FLogStream.WriteLine('');
FLogStream.WriteLine('=================================================');
FLogStream.WriteLine('日志开始: ' + FormatDateTime('yyyy-mm-dd hh:nn:ss', Now));
FLogStream.WriteLine('应用程序: ' + ExtractFileName(ParamStr(0)));
FLogStream.WriteLine('=================================================');
FLogStream.WriteLine('');
FIsInitialized := True;
except
on E: Exception do
begin
if FShowDialogs then
ShowMessage('初始化日志系统失败: ' + E.Message);
end;
end;
end;
class procedure TErrorLogger.ReleaseInstance;
begin
if Assigned(FInstance) then
begin
FInstance.Free;
FInstance := nil;
end;
end;
procedure TErrorLogger.Log(const Msg: string; Level: TLogLevel);
var
LogMsg: string;
begin
LogMsg := Format('[%s] [%s] %s',
[FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', Now),
GetLogLevelString(Level),
Msg]);
WriteToLog(LogMsg);
end;
procedure TErrorLogger.Log(const Msg: string; E: Exception; Level: TLogLevel);
var
LogMsg: string;
begin
if Assigned(E) then
LogMsg := Format('[%s] [%s] %s - Exception: %s (%s)',
[FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', Now),
GetLogLevelString(Level),
Msg,
E.ClassName,
E.Message])
else
LogMsg := Format('[%s] [%s] %s',
[FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', Now),
GetLogLevelString(Level),
Msg]);
WriteToLog(LogMsg);
end;
procedure TErrorLogger.LogFormat(const Fmt: string; const Args: array of const; Level: TLogLevel);
begin
Log(Format(Fmt, Args), Level);
end;
procedure TErrorLogger.ShowErrorDialog(const Msg: string; E: Exception);
var
ErrorMsg: string;
begin
if not FShowDialogs then Exit;
if Assigned(E) then
ErrorMsg := Msg + #13#10 + #13#10 + '错误详情: ' + E.Message
else
ErrorMsg := Msg;
MessageDlg(ErrorMsg, mtError, [mbOK], 0);
end;
procedure TErrorLogger.ShowInfoDialog(const Msg: string);
begin
if not FShowDialogs then Exit;
MessageDlg(Msg, mtInformation, [mbOK], 0);
end;
procedure TErrorLogger.ShowWarningDialog(const Msg: string);
begin
if not FShowDialogs then Exit;
MessageDlg(Msg, mtWarning, [mbOK], 0);
end;
procedure TErrorLogger.WriteToLog(const Msg: string);
begin
if not FIsInitialized then
InitializeLogger;
try
if Assigned(FLogStream) then
FLogStream.WriteLine(Msg);
except
// 忽略写入日志时的错误
end;
end;
initialization
// 不在这里创建实例,而是在需要时通过GetInstance创建
finalization
TErrorLogger.ReleaseInstance;
end.