forked from exilon/QuickLib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Quick.Log.pas
302 lines (263 loc) · 8.68 KB
/
Quick.Log.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
{ ***************************************************************************
Copyright (c) 2016-2018 Kike Pérez
Unit : Quick.Log
Description : Threadsafe Log
Author : Kike Pérez
Version : 1.18
Created : 10/04/2016
Modified : 08/04/2018
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
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.Log;
{$i QuickLib.inc}
interface
uses
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
Classes,
Quick.Commons,
{$IFNDEF FPC}
System.IOUtils,
{$ELSE}
Quick.Files,
{$IFDEF LINUX}
syncObjs,
{$ENDIF}
{$ENDIF}
SysUtils;
type
TMemoryLog = class
private
fLines : TStrings;
fEnabled : Boolean;
function GetLogText : string;
public
constructor Create;
destructor Destroy; override;
property Lines : TStrings read fLines write fLines;
property Text : string read GetLogText;
property Enabled : Boolean read fEnabled write fEnabled;
end;
TQuickLog = class
private
fLogFileName : string;
fCurrentDateToFileName : Boolean;
fHideHour : Boolean;
fFMTName : string;
fVerbose : TLogVerbose;
fLimitLogSize : Int64;
fCurrentLogSize : Int64;
fShowEventTypes : Boolean;
fShowHeaderInfo : Boolean;
fCheckFileInUse : Boolean;
fMemoryLog : TMemoryLog;
function GetLogFileName : string;
procedure WriteLog(cMsg : string);
public
property Verbose : TLogVerbose read fVerbose write fVerbose;
property LogFileName : string read GetLogFileName;
property HideHour : Boolean read fHideHour write fHideHour;
property ShowEventType : Boolean read fShowEventTypes write fShowEventTypes;
property ShowHeaderInfo : Boolean read fShowHeaderInfo write fShowHeaderInfo;
property CheckFileInUse : Boolean read fCheckFileInUse write fCheckFileInUse;
property MemoryLog : TMemoryLog read fMemoryLog write fMemoryLog;
constructor Create;
destructor Destroy; override;
function SetLog(logname : string; AddCurrentDateToFileName : Boolean; LimitSizeInMB : Integer = 0) : Boolean;
procedure Add(const cMsg : string; cEventType : TLogEventType = TLogEventType.etInfo); overload;
procedure Add(const cFormat : string; cParams : array of TVarRec ; cEventType : TLogEventType = TLogEventType.etInfo); overload;
end;
var
CS : TRTLCriticalSection;
Log : TQuickLog;
implementation
constructor TMemoryLog.Create;
begin
inherited;
fLines := TStringList.Create;
fEnabled := False;
end;
destructor TMemoryLog.Destroy;
begin
if Assigned(fLines) then fLines.Free;
inherited;
end;
function TMemoryLog.GetLogText : string;
begin
Result := fLines.Text;
end;
constructor TQuickLog.Create;
begin
inherited;
fVerbose := LOG_ALL;
fLimitLogSize := 0;
fShowEventTypes := True;
fShowHeaderInfo := True;
fCheckFileInUse := False;
fMemoryLog := TMemoryLog.Create;
end;
destructor TQuickLog.Destroy;
begin
if Assigned(fMemoryLog) then fMemoryLog.Free;
inherited;
end;
{Returns date + time in english format (to add to filename}
function TQuickLog.GetLogFileName : string;
begin
Result := '';
if fCurrentDateToFileName then
begin
try
//Checks if needs to show time or not
if HideHour then Result := FormatDateTime('yyyymmdd', Now())
else Result := FormatDateTime('yyyymmdd_hhmm', Now());
Result := Format(fFMTName,[Result]);
except
Result := 'Error';
end;
end
else Result := fLogFileName;
end;
{$IFDEF FPC}
function OSVersion: String;
begin
Result:={$I %FPCTARGETOS%}+'-'+{$I %FPCTARGETCPU%};
end;
{$ENDIF}
function TQuickLog.SetLog(logname : string; AddCurrentDateToFileName : Boolean; LimitSizeInMB : Integer = 0) : Boolean;
begin
if logname = '' then logname := TPath.GetDirectoryName(ParamStr(0)) + '\' + TPath.GetFileNameWithoutExtension(ParamStr(0)) + '.log';
fFMTName := ExtractFilePath(logname) + ExtractFileNameWithoutExt(logname) + '_%s' + ExtractFileExt(logname);
fHideHour := True;
fCurrentDateToFileName := AddCurrentDateToFileName;
fLogFileName := logname;
//Checks if logfile is too big and deletes
fLimitLogSize := LimitSizeInMB * 1024 * 1024;
if (fLimitLogSize > 0) and (TFile.Exists(logname)) then
begin
try
fCurrentLogSize := TFile.GetSize(logname);
if fCurrentLogSize > fLimitLogSize then if DeleteFile(logname) then fCurrentLogSize := 0;
except
raise Exception.Create('can''t access to log file!');
end;
end;
//Checks if it's in use
if (fCheckFileInUse) and (TFile.IsInUse(logname)) Then fLogFileName := Format('%s_(1).%s',[ExtractFileNameWithoutExt(logname),ExtractFileExt(logname)]);
//writes header info
if fShowHeaderInfo then
begin
try
Self.WriteLog(FillStr('-',70));
Self.WriteLog(Format('Application : %s %s',[ExtractFilenameWithoutExt(ParamStr(0)),GetAppVersionFullStr]));
Self.WriteLog(Format('Path : %s',[ExtractFilePath(ParamStr(0))]));
Self.WriteLog(Format('CPU cores : %d',[CPUCount]));
Self.WriteLog(Format('OS version : %s',{$IFDEF FPC}[OSVersion]{$ELSE}[TOSVersion.ToString]{$ENDIF}));
Self.WriteLog(Format('Host : %s',[GetComputerName]));
Self.WriteLog(Format('Username : %s',[Trim(GetLoggedUserName)]));
Self.WriteLog(Format('Started : %s',[NowStr]));
{$IFDEF MSWINDOWS}
if IsService then Self.WriteLog('AppType : Service')
else if System.IsConsole then Self.WriteLog('AppType : Console');
{$ENDIF}
if IsDebug then Self.WriteLog('Debug mode : On');
Self.WriteLog(FillStr('-',70));
except
on E : Exception do Self.WriteLog('Can''t get info: ' + e.message);
end;
end;
Result := True;
end;
procedure TQuickLog.Add(const cMsg : string; cEventType : TLogEventType = TLogEventType.etInfo);
begin
//Check Log Verbose level
if cEventType in fVerbose then
begin
if fShowEventTypes then Self.WriteLog(Format('%s [%s] %s',[DateTimeToStr(Now()),EventStr[Integer(cEventType)],cMsg]))
else Self.WriteLog(Format('%s %s',[DateTimeToStr(Now()),cMsg]));
end;
end;
procedure TQuickLog.WriteLog(cMsg : string);
var
stream: TFileStream;
logname : string;
LBuffer : TBytes;
LByteOrderMark: TBytes;
LOffset : Integer;
LEncoding, DestEncoding: TEncoding;
begin
//Checks if need to add date to filename
logname := GetLogFileName;
EnterCriticalSection(CS);
try
cMsg := cMsg + #13#10;
LEncoding:= TEncoding.Unicode;
DestEncoding := TEncoding.Unicode;
SetLength(LBuffer, length(cMsg) * sizeof(char));
if cMsg <> '' then Move(cMsg[1], lbuffer[0], Length(lbuffer));
LOffset := TEncoding.GetBufferEncoding(LBuffer, LEncoding);
LBuffer := LEncoding.Convert(LEncoding, DestEncoding, LBuffer,
LOffset, Length(LBuffer) - LOffset);
if TFile.Exists(logname) then
begin
stream := TFileStream.Create(logname, fmOpenReadWrite or fmShareDenyWrite);
stream.Position := stream.Size;
end
else
begin
stream := TFileStream.Create(logname, fmCreate or fmShareDenyWrite);
LByteOrderMark := DestEncoding.GetPreamble;
stream.Write(LByteOrderMark[0], Length(LByteOrderMark));
end;
with stream do
begin
try
Write(LBuffer[0], Length(LBuffer));
fCurrentLogSize := fCurrentLogSize + Length(LBuffer);
finally
Free;
end;
end;
//writes internal log
if fMemoryLog.Enabled then
begin
fMemoryLog.Lines.Add(cMsg);
end;
//check if limits max size
try
if (fLimitLogSize > 0) and (fCurrentLogSize > fLimitLogSize) then if DeleteFile(logname) then fCurrentLogSize := 0;
except
//
end;
finally
LeaveCriticalSection(CS);
end;
end;
procedure TQuickLog.Add(const cFormat : string; cParams : array of TVarRec ; cEventType : TLogEventType = TLogEventType.etInfo);
begin
Self.Add(Format(cFormat,cParams),cEventType);
end;
initialization
{$IF DEFINED(FPC) AND DEFINED(LINUX)}
InitCriticalSection(CS);
{$ELSE}
InitializeCriticalSection(CS);
{$ENDIF}
finalization
{$IF DEFINED(FPC) AND DEFINED(LINUX)}
DoneCriticalsection(CS);
{$ELSE}
DeleteCriticalSection(CS);
{$ENDIF}
end.