forked from exilon/QuickLogger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Quick.Logger.Provider.Files.pas
390 lines (354 loc) · 11.5 KB
/
Quick.Logger.Provider.Files.pas
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
{ ***************************************************************************
Copyright (c) 2016-2019 Kike Pérez
Unit : Quick.Logger.Provider.Files
Description : Log Console Provider
Author : Kike Pérez
Version : 1.24
Created : 12/10/2017
Modified : 21/02/2019
This file is part of QuickLogger: https://github.com/exilon/QuickLogger
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Logger.Provider.Files;
{$i QuickLib.inc}
interface
uses
Classes,
SysUtils,
{$IFDEF FPC}
Quick.Files,
zipper,
{$ELSE}
System.IOUtils,
System.Zip,
{$ENDIF}
Quick.Commons,
Quick.Logger;
type
TLogFileProvider = class (TLogProviderBase,IRotable)
private
fLogWriter : TStreamWriter;
fFileName : string;
fMaxRotateFiles : Integer;
fMaxFileSizeInMB : Integer;
fLimitLogSize : Int64;
fDailyRotate : Boolean;
fCompressRotatedFiles : Boolean;
fRotatedFilesPath : string;
fFileCreationDate : TDateTime;
fShowEventTypes : Boolean;
fShowHeaderInfo : Boolean;
fIsRotating : Boolean;
fUnderlineHeaderEventType: Boolean;
fAutoFlush : Boolean;
fAutoFileName : Boolean;
procedure WriteToStream(const cMsg : string);
procedure CompressLogFile(const cFileName : string);
function GetLogFileBackup(cNumBackup : Integer; zipped : Boolean) : string;
function CheckNeedRotate : Boolean;
public
constructor Create; override;
destructor Destroy; override;
property FileName : string read fFileName write fFileName;
{$IFDEF MSWINDOWS}
property AutoFileNameByProcess : Boolean read fAutoFileName write fAutoFileName;
{$ENDIF}
property MaxRotateFiles : Integer read fMaxRotateFiles write fMaxRotateFiles;
property MaxFileSizeInMB : Integer read fMaxFileSizeInMB write fMaxFileSizeInMB;
property DailyRotate : Boolean read fDailyRotate write fDailyRotate;
property RotatedFilesPath : string read fRotatedFilesPath write fRotatedFilesPath;
property CompressRotatedFiles : Boolean read fCompressRotatedFiles write fCompressRotatedFiles;
property ShowEventType : Boolean read fShowEventTypes write fShowEventTypes;
property ShowHeaderInfo : Boolean read fShowHeaderInfo write fShowHeaderInfo;
property UnderlineHeaderEventType : Boolean read fUnderlineHeaderEventType write fUnderlineHeaderEventType;
property AutoFlush : Boolean read fAutoFlush write fAutoFlush;
procedure Init; override;
procedure Restart; override;
procedure WriteLog(cLogItem : TLogItem); override;
procedure RotateLog;
end;
{$IFDEF MSWINDOWS}
function GetCurrentProcessId : Cardinal; stdcall; external 'kernel32.dll';
{$ENDIF}
var
GlobalLogFileProvider : TLogFileProvider;
implementation
constructor TLogFileProvider.Create;
begin
inherited;
fFileName := '';
fIsRotating := False;
fMaxRotateFiles := 5;
fMaxFileSizeInMB := 20;
fDailyRotate := False;
fCompressRotatedFiles := False;
fShowEventTypes := True;
fShowHeaderInfo := True;
fUnderlineHeaderEventType := False;
fRotatedFilesPath := '';
fAutoFlush := False;
fAutoFileName := False;
LogLevel := LOG_ALL;
IncludedInfo := [iiAppName,iiHost,iiUserName,iiOSVersion];
end;
destructor TLogFileProvider.Destroy;
begin
if Assigned(fLogWriter) then fLogWriter.Free;
inherited;
end;
procedure CreateNewLogFile(const aFilename : string);
var
fs : TFileStream;
begin
//resolve windows filesystem tunneling creation date?
fs := TFile.Create(aFilename);
try
//do nothing...created to set new creationdate
finally
fs.Free;
end;
TFile.SetCreationTime(aFilename,Now());
end;
procedure TLogFileProvider.Init;
var
FileMode : Word;
fs : TFileStream;
begin
if fFileName = '' then
begin
{$IFNDEF ANDROID}
fFileName := TPath.GetDirectoryName(ParamStr(0)) + PathDelim + TPath.GetFileNameWithoutExtension(ParamStr(0)) + '.log';
{$ELSE}
fFileName := TPath.GetDocumentsPath + PathDelim + 'logger.log';
{$ENDIF}
end;
if fFileName.StartsWith('.'+PathDelim) then fFileName := StringReplace(fFileName,'.'+PathDelim,TPath.GetDirectoryName(ParamStr(0)) + PathDelim,[])
else if ExtractFilePath(fFileName) = '' then fFileName := TPath.GetDirectoryName(ParamStr(0)) + PathDelim + fFileName;
{$IFDEF MSWINDOWS}
if fAutoFileName then fFileName := Format('%s\%s_%d.log',[TPath.GetDirectoryName(fFileName),TPath.GetFileNameWithoutExtension(fFileName),GetCurrentProcessId]);
{$ENDIF}
if fMaxFileSizeInMB > 0 then fLimitLogSize := fMaxFileSizeInMB * 1024 * 1024
else fLimitLogSize := 0;
if TFile.Exists(fFileName) then
begin
fFileCreationDate := TFile.GetCreationTime(fFileName);
FileMode := fmOpenWrite or fmShareDenyWrite;
end
else
begin
FileMode := fmCreate or fmShareDenyWrite;
fFileCreationDate := Now();
//resolve windows filesystem tunneling creation date
CreateNewLogFile(fFileName);
end;
//create stream file
fs := TFileStream.Create(fFileName, FileMode);
try
fs.Seek(0,TSeekOrigin.soEnd);
fLogWriter := TStreamWriter.Create(fs,TEncoding.Default,32);
fLogWriter.AutoFlush := fAutoFlush;
fLogWriter.OwnStream;
//check if need to rotate
if CheckNeedRotate then
begin
RotateLog;
Exit;
end;
//writes header info
if fShowHeaderInfo then
begin
WriteToStream(FillStr('-',70));
if iiAppName in IncludedInfo then
begin
{$IFDEF MSWINDOWS}
WriteToStream(Format('Application : %s %s',[SystemInfo.AppName,SystemInfo.AppVersion]));
{$ELSE}
WriteToStream(Format('Application : %s %s',[SystemInfo.AppName,SystemInfo.AppVersion]));
{$ENDIF}
end;
WriteToStream(Format('Path : %s',[SystemInfo.AppPath]));
WriteToStream(Format('CPU cores : %d',[SystemInfo.CPUCores]));
if iiOSVersion in IncludedInfo then WriteToStream(Format('OS version : %s',[SystemInfo.OSVersion]));
//{$IFDEF MSWINDOWS}
if iiHost in IncludedInfo then WriteToStream(Format('Host : %s',[SystemInfo.HostName]));
if iiUserName in IncludedInfo then WriteToStream(Format('Username : %s',[SystemInfo.UserName]));
//{$ENDIF}
WriteToStream(Format('Started : %s',[DateTimeToStr(Now(),FormatSettings)]));
{$IFDEF MSWINDOWS}
if IsService then WriteToStream('AppType : Service')
else if System.IsConsole then WriteToStream('AppType : Console');
if IsDebug then WriteToStream('Debug mode : On');
{$ENDIF}
WriteToStream(FillStr('-',70));
end;
except
fs.Free;
raise;
end;
//creates the threadlog
inherited;
end;
procedure TLogFileProvider.WriteToStream(const cMsg : string);
begin
try
//check if need to rotate
if CheckNeedRotate then RotateLog;
//writes to stream file
fLogWriter.WriteLine(cMsg);
//needs to flush if autoflush??
if not fAutoFlush then fLogWriter.Flush;
except
raise ELogger.Create('Error writting to file log!');
end;
end;
procedure TLogFileProvider.WriteLog(cLogItem : TLogItem);
begin
if CustomMsgOutput then
begin
WriteToStream(cLogItem.Msg);
Exit;
end;
if cLogItem.EventType = etHeader then
begin
WriteToStream(cLogItem.Msg);
if fUnderlineHeaderEventType then WriteToStream(FillStr('-',cLogItem.Msg.Length));
end
else
begin
if fShowEventTypes then WriteToStream(Format('%s [%s] %s',[DateTimeToStr(cLogItem.EventDate,FormatSettings),EventTypeName[cLogItem.EventType],cLogItem.Msg]))
else WriteToStream(Format('%s %s',[DateTimeToStr(cLogItem.EventDate,FormatSettings),cLogItem.Msg]));
end;
end;
function TLogFileProvider.GetLogFileBackup(cNumBackup : Integer; zipped : Boolean) : string;
var
LogExt : string;
LogName : string;
zipExt : string;
begin
if zipped then zipExt := '.zip'
else zipExt := '';
if fRotatedFilesPath = '' then
begin
LogName := TPath.GetFileNameWithoutExtension(fFileName);
end
else
begin
ForceDirectories(fRotatedFilesPath);
LogName := IncludeTrailingPathDelimiter(fRotatedFilesPath) + TPath.GetFileNameWithoutExtension(fFilename);
end;
LogExt := TPath.GetExtension(fFileName);
Result := Format('%s.%d%s%s',[LogName,cNumBackup,LogExt,zipExt]);
end;
procedure TLogFileProvider.Restart;
begin
Stop;
if Assigned(fLogWriter) then fLogWriter.Free;
Init;
end;
procedure TLogFileProvider.RotateLog;
var
RotateFile : string;
i : Integer;
begin
if fIsRotating then Exit;
fIsRotating := True;
try
//frees stream file
if Assigned(fLogWriter) then fLogWriter.Free;
try
//delete older log backup and zip
RotateFile := GetLogFileBackup(fMaxRotateFiles,True);
if TFile.Exists(RotateFile) then TFile.Delete(RotateFile);
RotateFile := GetLogFileBackup(fMaxRotateFiles,False);
if TFile.Exists(RotateFile) then TFile.Delete(RotateFile);
//rotates older log backups or zips
for i := fMaxRotateFiles - 1 downto 1 do
begin
RotateFile := GetLogFileBackup(i,True);
if TFile.Exists(RotateFile) then TFile.Move(RotateFile,GetLogFileBackup(i + 1,True));
RotateFile := GetLogFileBackup(i,False);
if TFile.Exists(RotateFile) then TFile.Move(RotateFile,GetLogFileBackup(i + 1,False));
end;
//rename current log
RotateFile := GetLogFileBackup(1,False);
TFile.Move(fFileName,RotateFile);
finally
//initialize stream file again
Init;
end;
finally
fIsRotating := False;
end;
//compress log file
if fCompressRotatedFiles then
begin
{$IFDEF FPC}
CompressLogFile(RotateFile);
{$ELSE}
TThread.CreateAnonymousThread(procedure
begin
CompressLogFile(RotateFile);
end
).Start;
{$ENDIF}
end;
end;
function TLogFileProvider.CheckNeedRotate: Boolean;
begin
if ((fLimitLogSize > 0) and (fLogWriter.BaseStream.Size > fLimitLogSize))
or ((fDailyRotate) and (not IsSameDay(fFileCreationDate,Now()))) then
Result := True
else Result := False;
end;
procedure TLogFileProvider.CompressLogFile(const cFileName : string);
{$IFDEF FPC}
var
zip : TZipper;
begin
try
zip := TZipper.Create;
try
zip.FileName := GetLogFileBackup(1,True);
zip.Entries.AddFileEntry(cFilename,ExtractFileName(cFilename));
zip.ZipAllFiles;
finally
zip.Free;
end;
TFile.Delete(cFileName);
except
raise ELogger.Create('Error trying to backup log file!');
end;
end;
{$ELSE}
var
zip : TZipFile;
begin
try
zip := TZipFile.Create;
try
zip.Open(GetLogFileBackup(1,True),zmWrite);
zip.Add(cFileName,'',TZipCompression.zcDeflate);
zip.Close;
finally
zip.Free;
end;
TFile.Delete(cFileName);
except
raise ELogger.Create('Error trying to backup log file!');
end;
end;
{$ENDIF}
initialization
GlobalLogFileProvider := TLogFileProvider.Create;
finalization
if Assigned(GlobalLogFileProvider) and (GlobalLogFileProvider.RefCount = 0) then GlobalLogFileProvider.Free;
end.