-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathQuick.Logger.pas
1813 lines (1640 loc) · 57.9 KB
/
Quick.Logger.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{ ***************************************************************************
Copyright (c) 2016-2022 Kike Pérez
Unit : Quick.Logger
Description : Threadsafe Multi Log File, Console, Email, etc...
Author : Kike Pérez
Version : 1.42
Created : 12/10/2017
Modified : 24/01/2022
This file is part of QuickLogger: https://github.com/exilon/QuickLogger
Needed libraries:
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.Logger;
{$i QuickLib.inc}
{.$DEFINE LOGGER_DEBUG}
{.$DEFINE LOGGER_DEBUG2}
interface
uses
{$IFDEF MSWINDOWS}
Windows,
{$IFDEF DELPHIXE7_UP}
{$ELSE}
SyncObjs,
{$ENDIF}
{$ENDIF}
Quick.Logger.Intf,
Quick.JSON.Utils,
Quick.Json.Serializer,
Classes,
Types,
SysUtils,
DateUtils,
{$IFDEF FPC}
fpjson,
fpjsonrtti,
{$IFDEF LINUX}
SyncObjs,
{$ENDIF}
Quick.Files,
Generics.Collections,
{$ELSE}
System.IOUtils,
System.Generics.Collections,
{$IFDEF DELPHIXE8_UP}
System.JSON,
{$ELSE}
Data.DBXJSON,
{$ENDIF}
{$ENDIF}
Quick.Threads,
Quick.Commons,
Quick.SysInfo;
const
QLVERSION = '1.46';
type
TEventType = (etHeader, etInfo, etSuccess, etWarning, etError, etCritical, etException, etDebug, etTrace, etDone, etCustom1, etCustom2);
TLogLevel = set of TEventType;
{$IFDEF DELPHIXE7_UP}
TEventTypeNames = array of string;
{$ELSE}
TEventTypeNames = array[0..11] of string;
{$ENDIF}
ELogger = class(Exception);
ELoggerInitializationError = class(Exception);
ELoggerLoadProviderError = class(Exception);
ELoggerSaveProviderError = class(Exception);
const
LOG_ONLYERRORS = [etHeader,etInfo,etError,etCritical,etException];
LOG_ERRORSANDWARNINGS = [etHeader,etInfo,etWarning,etError,etCritical,etException];
LOG_BASIC = [etInfo,etSuccess,etWarning,etError,etCritical,etException];
LOG_ALL = [etHeader,etInfo,etSuccess,etDone,etWarning,etError,etCritical,etException,etCustom1,etCustom2];
LOG_TRACE = [etHeader,etInfo,etSuccess,etDone,etWarning,etError,etCritical,etException,etTrace];
LOG_DEBUG = [etHeader,etInfo,etSuccess,etDone,etWarning,etError,etCritical,etException,etTrace,etDebug];
LOG_VERBOSE : TLogLevel = [Low(TEventType)..high(TEventType)];
{$IFDEF DELPHIXE7_UP}
DEF_EVENTTYPENAMES : TEventTypeNames = ['','INFO','SUCC','WARN','ERROR','CRITICAL','EXCEPT','DEBUG','TRACE','DONE','CUST1','CUST2'];
{$ELSE}
DEF_EVENTTYPENAMES : TEventTypeNames = ('','INFO','SUCC','WARN','ERROR','CRITICAL','EXCEPT','DEBUG','TRACE','DONE','CUST1','CUST2');
{$ENDIF}
HTMBR = '<BR>';
DEF_QUEUE_SIZE = 10;
DEF_QUEUE_PUSH_TIMEOUT = 1500;
DEF_QUEUE_POP_TIMEOUT = 200;
DEF_WAIT_FLUSH_LOG = 30;
DEF_USER_AGENT = 'Quick.Logger Agent';
type
TLogProviderStatus = (psNone, psStopped, psInitializing, psRunning, psDraining, psStopping, psRestarting);
{$IFNDEF FPC}
{$IF Defined(NEXTGEN) OR Defined(OSX) OR Defined(LINUX)}
TSystemTime = TDateTime;
{$ENDIF}
{$ENDIF}
TLogInfoField = (iiAppName, iiHost, iiUserName, iiEnvironment, iiPlatform, iiOSVersion, iiExceptionInfo, iiExceptionStackTrace, iiThreadId, iiProcessId);
TIncludedLogInfo = set of TLogInfoField;
TProviderErrorEvent = procedure(const aProviderName, aError : string) of object;
{$IFNDEF DELPHIRX10_UP}
TThreadID = DWORD;
{$ENDIF}
TLogItem = class
private
fEventType : TEventType;
fMsg : string;
fEventDate : TDateTime;
fThreadId : TThreadID;
public
constructor Create;
property EventType : TEventType read fEventType write fEventType;
property Msg : string read fMsg write fMsg;
property EventDate : TDateTime read fEventDate write fEventDate;
property ThreadId : TThreadID read fThreadId write fThreadId;
function EventTypeName : string;
function Clone : TLogItem; virtual;
end;
TLogExceptionItem = class(TLogItem)
private
fException : string;
fStackTrace : string;
public
property Exception : string read fException write fException;
property StackTrace : string read fStackTrace write fStackTrace;
function Clone : TLogItem; override;
end;
TLogQueue = class(TThreadedQueueList<TLogItem>);
ILogTags = interface
['{046ED03D-9EE0-49BC-BBD7-FA108EA1E0AA}']
function GetTag(const aKey : string) : string;
procedure SetTag(const aKey : string; const aValue : string);
function TryGetValue(const aKey : string; out oValue : string) : Boolean;
procedure Add(const aKey, aValue : string);
property Items[const Key: string]: string read GetTag write SetTag; default;
end;
ILogProvider = interface
['{0E50EA1E-6B69-483F-986D-5128DA917ED8}']
procedure Init;
procedure Restart;
//procedure Flush;
procedure Stop;
procedure Drain;
function AcceptItem(cLogItem : TLogItem): boolean;
procedure EnQueueItem(cLogItem : TLogItem);
procedure WriteLog(cLogItem : TLogItem);
function IsQueueable : Boolean;
procedure IncAndCheckErrors;
function Status : TLogProviderStatus;
procedure SetStatus(cStatus : TLogProviderStatus);
procedure SetLogTags(cLogTags : ILogTags);
function IsSendLimitReached(cEventType : TEventType): Boolean;
function GetLogLevel : TLogLevel;
function IsEnabled : Boolean;
function GetVersion : string;
function GetName : string;
function GetQueuedLogItems : Integer;
{$IF DEFINED(DELPHIXE7_UP)}// AND NOT DEFINED(NEXTGEN)}
function ToJson(aIndent : Boolean = True) : string;
procedure FromJson(const aJson : string);
procedure SaveToFile(const aJsonFile : string);
procedure LoadFromFile(const aJsonFile : string);
{$ENDIF}
end;
IRotable = interface
['{EF5E004F-C7BE-4431-8065-6081FEB3FC65}']
procedure RotateLog;
end;
TThreadLog = class(TThread)
private
fLogQueue : TLogQueue;
fProvider : ILogProvider;
public
constructor Create;
destructor Destroy; override;
property LogQueue : TLogQueue read fLogQueue write fLogQueue;
property Provider : ILogProvider read fProvider write fProvider;
procedure Execute; override;
end;
TSendLimitTimeRange = (slNoLimit, slByDay, slByHour, slByMinute, slBySecond);
TLogSendLimit = class
private
fCurrentNumSent : Integer;
fFirstSent : TDateTime;
fLastSent : TDateTime;
fTimeRange : TSendLimitTimeRange;
fLimitEventTypes : TLogLevel;
fNumBlocked : Int64;
fMaxSent: Integer;
public
constructor Create;
property TimeRange : TSendLimitTimeRange read fTimeRange write fTimeRange;
property LimitEventTypes : TLogLevel read fLimitEventTypes write fLimitEventTypes;
property MaxSent : Integer read fMaxSent write fMaxSent;
function IsLimitReached(cEventType : TEventType): Boolean;
end;
{$IFDEF FPC}
TQueueErrorEvent = procedure(const msg : string) of object;
TFailToLogEvent = procedure(const aProviderName : string) of object;
TStartEvent = procedure(const aProviderName : string) of object;
TRestartEvent = procedure(const aProviderName : string) of object;
TCriticalErrorEvent = procedure(const aProviderName, ErrorMessage : string) of object;
TSendLimitsEvent = procedure(const aProviderName : string) of object;
TStatusChangedEvent = procedure(aProviderName : string; status : TLogProviderStatus) of object;
TProviderFilterEvent = function (aLogItem : TLogItem) : boolean;
{$ELSE}
TQueueErrorEvent = reference to procedure(const msg : string);
TFailToLogEvent = reference to procedure(const aProviderName : string);
TStartEvent = reference to procedure(const aProviderName : string);
TRestartEvent = reference to procedure(const aProviderName : string);
TCriticalErrorEvent = reference to procedure(const aProviderName, ErrorMessage : string);
TSendLimitsEvent = reference to procedure(const aProviderName : string);
TStatusChangedEvent = reference to procedure(aProviderName : string; status : TLogProviderStatus);
TProviderFilterEvent = reference to function (aLogItem : TLogItem) : boolean;
{$ENDIF}
TJsonOutputOptions = class
private
fUseUTCTime : Boolean;
fTimeStampName : string;
public
property UseUTCTime : Boolean read fUseUTCTime write fUseUTCTime;
property TimeStampName : string read fTimeStampName write fTimeStampName;
end;
TLogTags = class(TInterfacedObject,ILogTags)
private
fTags : TDictionary<string,string>;
function GetTag(const aKey : string) : string;
procedure SetTag(const aKey : string; const aValue : string);
public
constructor Create;
destructor Destroy; override;
property Items[const Key: string]: string read GetTag write SetTag; default;
function TryGetValue(const aKey : string; out oValue : string) : Boolean;
procedure Add(const aKey, aValue : string);
end;
TLogProviderBase = class(TInterfacedObject,ILogProvider)
protected
fThreadLog : TThreadLog;
private
fName : string;
fLogQueue : TLogQueue;
fLogLevel : TLogLevel;
fFormatSettings : TFormatSettings;
fEnabled : Boolean;
fTimePrecission : Boolean;
fFails : Integer;
fRestartTimes : Integer;
fFailsToRestart : Integer;
fMaxFailsToRestart : Integer;
fMaxFailsToStop : Integer;
fUsesQueue : Boolean;
fStatus : TLogProviderStatus;
fAppName : string;
fEnvironment : string;
fPlatformInfo : string;
fEventTypeNames : TEventTypeNames;
fSendLimits : TLogSendLimit;
fOnFailToLog: TFailToLogEvent;
fOnRestart: TRestartEvent;
fOnCriticalError : TCriticalErrorEvent;
fOnStatusChanged : TStatusChangedEvent;
fOnQueueError: TQueueErrorEvent;
fOnSendLimits: TSendLimitsEvent;
fIncludedInfo : TIncludedLogInfo;
fIncludedTags : TArray<string>;
fSystemInfo : TSystemInfo;
fCustomMsgOutput : Boolean;
fOnNotifyError : TProviderErrorEvent;
fOnFilterItem : TProviderFilterEvent;
procedure SetTimePrecission(Value : Boolean);
procedure SetEnabled(aValue : Boolean);
function GetQueuedLogItems : Integer;
procedure EnQueueItem(cLogItem : TLogItem);
function GetEventTypeName(cEventType : TEventType) : string;
procedure SetEventTypeName(cEventType: TEventType; const cValue : string);
function IsSendLimitReached(cEventType : TEventType): Boolean;
procedure SetMaxFailsToRestart(const Value: Integer);
protected
fJsonOutputOptions : TJsonOutputOptions;
fCustomTags : ILogTags;
fCustomFormatOutput : string;
function LogItemToLine(cLogItem : TLogItem; aShowTimeStamp, aShowEventTypes : Boolean) : string; overload;
function LogItemToJsonObject(cLogItem: TLogItem): TJSONObject; overload;
function LogItemToJson(cLogItem : TLogItem) : string; overload;
function LogItemToHtml(cLogItem: TLogItem): string;
function LogItemToText(cLogItem: TLogItem): string;
function LogItemToFormat(cLogItem : TLogItem) : string;
{$IFDEF DELPHIXE8_UP}
function LogItemToFormat2(cLogItem : TLogItem) : string;
{$ENDIF}
function ResolveFormatVariable(const cToken : string; cLogItem: TLogItem) : string;
procedure IncAndCheckErrors;
procedure SetStatus(cStatus : TLogProviderStatus);
procedure SetLogTags(cLogTags : ILogTags);
function GetLogLevel : TLogLevel;
property SystemInfo : TSystemInfo read fSystemInfo;
procedure NotifyError(const aError : string);
public
constructor Create; virtual;
destructor Destroy; override;
procedure Init; virtual;
procedure Restart; virtual; abstract;
procedure Stop; virtual;
procedure Drain;
procedure WriteLog(cLogItem : TLogItem); virtual; abstract;
function IsQueueable : Boolean;
function AcceptItem(cLogItem : TLogItem): boolean;
property Name : string read fName write fName;
property LogLevel : TLogLevel read fLogLevel write fLogLevel;
{$IFDEF DELPHIXE7_UP}[TNotSerializableProperty]{$ENDIF}
property FormatSettings : TFormatSettings read fFormatSettings write fFormatSettings;
property TimePrecission : Boolean read fTimePrecission write SetTimePrecission;
{$IFDEF DELPHIXE7_UP}[TNotSerializableProperty]{$ENDIF}
property Fails : Integer read fFails write fFails;
property MaxFailsToRestart : Integer read fMaxFailsToRestart write SetMaxFailsToRestart;
property MaxFailsToStop : Integer read fMaxFailsToStop write fMaxFailsToStop;
property CustomMsgOutput : Boolean read fCustomMsgOutput write fCustomMsgOutput;
property CustomFormatOutput : string read fCustomFormatOutput write fCustomFormatOutput;
property OnFailToLog : TFailToLogEvent read fOnFailToLog write fOnFailToLog;
property OnFilterItem : TProviderFilterEvent read fOnFilterItem write fOnFilterItem;
property OnRestart : TRestartEvent read fOnRestart write fOnRestart;
property OnQueueError : TQueueErrorEvent read fOnQueueError write fOnQueueError;
property OnCriticalError : TCriticalErrorEvent read fOnCriticalError write fOnCriticalError;
property OnStatusChanged : TStatusChangedEvent read fOnStatusChanged write fOnStatusChanged;
property OnSendLimits : TSendLimitsEvent read fOnSendLimits write fOnSendLimits;
{$IFDEF DELPHIXE7_UP}[TNotSerializableProperty]{$ENDIF}
property QueueCount : Integer read GetQueuedLogItems;
property UsesQueue : Boolean read fUsesQueue write fUsesQueue;
property Enabled : Boolean read fEnabled write SetEnabled;
property EventTypeName[cEventType : TEventType] : string read GetEventTypeName write SetEventTypeName;
property SendLimits : TLogSendLimit read fSendLimits write fSendLimits;
property AppName : string read fAppName write fAppName;
property Environment : string read fEnvironment write fEnvironment;
property PlatformInfo : string read fPlatformInfo write fPlatformInfo;
property IncludedInfo : TIncludedLogInfo read fIncludedInfo write fIncludedInfo;
property IncludedTags : TArray<string> read fIncludedTags write fIncludedTags;
function Status : TLogProviderStatus;
function StatusAsString : string; overload;
class function StatusAsString(cStatus : TLogProviderStatus) : string; overload;
function GetVersion : string;
function IsEnabled : Boolean;
function GetName : string;
{$IF DEFINED(DELPHIXE7_UP)}// AND NOT DEFINED(NEXTGEN)}
function ToJson(aIndent : Boolean = True) : string;
procedure FromJson(const aJson : string);
procedure SaveToFile(const aJsonFile : string);
procedure LoadFromFile(const aJsonFile : string);
{$ENDIF}
end;
{$IF DEFINED(DELPHIXE7_UP)}// AND NOT DEFINED(NEXTGEN)}
TLogProviderList = class(TList<ILogProvider>)
public
function ToJson(aIndent : Boolean = True) : string;
procedure FromJson(const aJson : string);
procedure LoadFromFile(const aJsonFile : string);
procedure SaveToFile(const aJsonFile : string);
end;
{$ELSE}
TLogProviderList = TList<ILogProvider>;
{$ENDIF}
TThreadProviderLog = class(TThread)
private
fLogQueue : TLogQueue;
fProviders : TLogProviderList;
public
constructor Create;
destructor Destroy; override;
property LogQueue : TLogQueue read fLogQueue write fLogQueue;
property Providers : TLogProviderList read fProviders write fProviders;
procedure Execute; override;
end;
TLogger = class(TInterfacedObject,ILogger)
private
fThreadProviderLog : TThreadProviderLog;
fLogQueue : TLogQueue;
fProviders : TLogProviderList;
fCustomTags : ILogTags;
fWaitForFlushBeforeExit : Integer;
fOnQueueError: TQueueErrorEvent;
fOwnErrorsProvider : TLogProviderBase;
fOnProviderError : TProviderErrorEvent;
function GetQueuedLogItems : Integer;
procedure EnQueueItem(cEventDate : TSystemTime; const cMsg : string; cEventType : TEventType); overload;
procedure EnQueueItem(cEventDate : TSystemTime; const cMsg : string; const cException, cStackTrace : string; cEventType : TEventType); overload;
procedure EnQueueItem(cLogItem : TLogItem); overload;
procedure OnGetHandledException(E : Exception);
procedure OnGetRuntimeError(const ErrorName : string; ErrorCode : Byte; ErrorPtr : Pointer);
procedure OnGetUnhandledException(ExceptObject: TObject; ExceptAddr: Pointer);
procedure NotifyProviderError(const aProviderName, aError : string);
procedure SetOwnErrorsProvider(const Value: TLogProviderBase);
{$IFNDEF FPC}
procedure OnProviderListNotify(Sender: TObject; const Item: ILogProvider; Action: TCollectionNotification);
{$ELSE}
procedure OnProviderListNotify(ASender: TObject; constref AItem: ILogProvider; AAction: TCollectionNotification);
{$ENDIF}
public
constructor Create;
destructor Destroy; override;
property Providers : TLogProviderList read fProviders write fProviders;
property RedirectOwnErrorsToProvider : TLogProviderBase read fOwnErrorsProvider write SetOwnErrorsProvider;
property WaitForFlushBeforeExit : Integer read fWaitForFlushBeforeExit write fWaitForFlushBeforeExit;
property OnProviderError : TProviderErrorEvent read fOnProviderError write fOnProviderError;
property QueueCount : Integer read GetQueuedLogItems;
property OnQueueError : TQueueErrorEvent read fOnQueueError write fOnQueueError;
property CustomTags : ILogTags read fCustomTags;
function ProvidersQueueCount : Integer;
function IsQueueEmpty : Boolean;
class function GetVersion : string;
procedure Add(const cMsg : string; cEventType : TEventType); overload;
procedure Add(const cMsg, cException, cStackTrace : string; cEventType : TEventType); overload;
procedure Add(const cMsg : string; cValues : array of {$IFDEF FPC}const{$ELSE}TVarRec{$ENDIF}; cEventType : TEventType); overload;
//simplify logging add
procedure Info(const cMsg : string); overload;
procedure Info(const cMsg : string; cValues : array of const); overload;
procedure Warn(const cMsg : string); overload;
procedure Warn(const cMsg : string; cValues : array of const); overload;
procedure Error(const cMsg : string); overload;
procedure Error(const cMsg : string; cValues : array of const); overload;
procedure Critical(const cMsg : string); overload;
procedure Critical(const cMsg : string; cValues : array of const); overload;
procedure Succ(const cMsg : string); overload;
procedure Succ(const cMsg : string; cValues : array of const); overload;
procedure Done(const cMsg : string); overload;
procedure Done(const cMsg : string; cValues : array of const); overload;
procedure Debug(const cMsg : string); overload;
procedure Debug(const cMsg : string; cValues : array of const); overload;
procedure Trace(const cMsg : string); overload;
procedure Trace(const cMsg : string; cValues : array of const); overload;
procedure &Except(const cMsg : string); overload;
procedure &Except(const cMsg : string; cValues : array of const); overload;
procedure &Except(const cMsg, cException, cStackTrace : string); overload;
procedure &Except(const cMsg : string; cValues: array of const; const cException, cStackTrace: string); overload;
end;
procedure Log(const cMsg : string; cEventType : TEventType); overload;
procedure Log(const cMsg : string; cValues : array of {$IFDEF FPC}const{$ELSE}TVarRec{$ENDIF}; cEventType : TEventType); overload;
var
Logger : TLogger;
GlobalLoggerHandledException : procedure(E : Exception) of object;
GlobalLoggerRuntimeError : procedure(const ErrorName : string; ErrorCode : Byte; ErrorPtr : Pointer) of object;
GlobalLoggerUnhandledException : procedure(ExceptObject: TObject; ExceptAddr: Pointer) of object;
implementation
{$IFNDEF MSWINDOWS}
procedure GetLocalTime(var vlocaltime : TDateTime);
begin
vlocaltime := Now();
end;
{$ENDIF}
procedure Log(const cMsg : string; cEventType : TEventType); overload;
begin
Logger.Add(cMsg,cEventType);
end;
procedure Log(const cMsg : string; cValues : array of {$IFDEF FPC}const{$ELSE}TVarRec{$ENDIF}; cEventType : TEventType); overload;
begin
Logger.Add(cMsg,cValues,cEventType);
end;
{ TLoggerProviderBase }
constructor TLogProviderBase.Create;
begin
fName := Self.ClassName;
fFormatSettings.DateSeparator := '/';
fFormatSettings.TimeSeparator := ':';
fFormatSettings.ShortDateFormat := 'DD-MM-YYY HH:NN:SS';
fFormatSettings.ShortTimeFormat := 'HH:NN:SS';
fStatus := psNone;
fTimePrecission := False;
fSendLimits := TLogSendLimit.Create;
{$IFDEF DELPHIXE7_UP}
fIncludedTags := [];
{$ELSE}
fIncludedTags := nil;
{$ENDIF}
fFails := 0;
fRestartTimes := 0;
fMaxFailsToRestart := 2;
fMaxFailsToStop := 0;
fFailsToRestart := fMaxFailsToRestart - 1;
fEnabled := False;
fUsesQueue := True;
fEventTypeNames := DEF_EVENTTYPENAMES;
fLogQueue := TLogQueue.Create(DEF_QUEUE_SIZE,DEF_QUEUE_PUSH_TIMEOUT,DEF_QUEUE_POP_TIMEOUT);
fEnvironment := '';
fPlatformInfo := '';
fIncludedInfo := [iiAppName,iiHost];
fSystemInfo := Quick.SysInfo.SystemInfo;
fJsonOutputOptions := TJsonOutputOptions.Create;
fJsonOutputOptions.UseUTCTime := False;
fJsonOutputOptions.TimeStampName := 'timestamp';
fAppName := fSystemInfo.AppName;
end;
destructor TLogProviderBase.Destroy;
begin
{$IFDEF LOGGER_DEBUG}
Writeln(Format('destroy object: %s',[Self.ClassName]));
Writeln(Format('%s.Queue = %d',[Self.ClassName,fLogQueue.QueueSize]));
{$ENDIF}
if Assigned(fLogQueue) then fLogQueue.Free;
if Assigned(fSendLimits) then fSendLimits.Free;
if Assigned(fJsonOutputOptions) then fJsonOutputOptions.Free;
inherited;
end;
function TLogProviderBase.AcceptItem(cLogItem : TLogItem): boolean;
begin
Result := cLogItem.EventType in GetLogLevel;
if Result and Assigned (fOnFilterItem) then
Result := OnFilterItem(cLogItem);
end;
procedure TLogProviderBase.Drain;
begin
//no receive more logs
SetStatus(TLogProviderStatus.psDraining);
fEnabled := False;
while fLogQueue.QueueSize > 0 do
begin
fLogQueue.PopItem.Free;
Sleep(0);
end;
SetStatus(TLogProviderStatus.psStopped);
//NotifyError(Format('Provider stopped!',[fMaxFailsToStop]));
end;
procedure TLogProviderBase.IncAndCheckErrors;
begin
Inc(fFails);
if Assigned(fOnFailToLog) then fOnFailToLog(fName);
if (fMaxFailsToStop > 0) and (fFails > fMaxFailsToStop) then
begin
//flush queue and stop provider from receiving new items
{$IFDEF LOGGER_DEBUG}
Writeln(Format('drain: %s (%d)',[Self.ClassName,fFails]));
{$ENDIF}
Drain;
NotifyError(Format('Max fails (%d) to Stop reached! It will be Drained & Stopped now!',[fMaxFailsToStop]));
if Assigned(fOnCriticalError) then fOnCriticalError(fName,'Max fails to Stop reached!');
end
else if fFailsToRestart = 0 then
begin
//try to restart provider
{$IFDEF LOGGER_DEBUG}
Writeln(Format('restart: %s (%d)',[Self.ClassName,fFails]));
{$ENDIF}
NotifyError(Format('Max fails (%d) to Restart reached! Restarting...',[fMaxFailsToRestart]));
SetStatus(TLogProviderStatus.psRestarting);
try
Restart;
except
on E : Exception do
begin
NotifyError(Format('Failed to restart: %s',[e.Message]));
//set as running to try again
SetStatus(TLogProviderStatus.psRunning);
Exit;
end;
end;
Inc(fRestartTimes);
NotifyError(Format('Provider Restarted. This occurs for %d time(s)',[fRestartTimes]));
fFailsToRestart := fMaxFailsToRestart-1;
if Assigned(fOnRestart) then fOnRestart(fName);
end
else
begin
Dec(fFailsToRestart);
NotifyError(Format('Failed %d time(s). Fails to restart %d/%d',[fFails,fFailsToRestart,fMaxFailsToRestart]));
end;
end;
function TLogProviderBase.Status : TLogProviderStatus;
begin
Result := fStatus;
end;
function TLogProviderBase.StatusAsString : string;
begin
Result := StatusAsString(fStatus);
end;
class function TLogProviderBase.StatusAsString(cStatus : TLogProviderStatus) : string;
const
{$IFDEF DELPHIXE7_UP}
LogProviderStatusStr : array of string = ['Nothing','Stopped','Initializing','Running','Draining','Stopping','Restarting'];
{$ELSE}
LogProviderStatusStr : array[0..6] of string = ('Nothing','Stopped','Initializing','Running','Draining','Stopping','Restarting');
{$ENDIF}
begin
Result := LogProviderStatusStr[Integer(cStatus)];
end;
procedure TLogProviderBase.Init;
begin
if not(fStatus in [psNone,psStopped,psRestarting]) then Exit;
{$IFDEF LOGGER_DEBUG}
Writeln(Format('init thread: %s',[Self.ClassName]));
{$ENDIF}
SetStatus(TLogProviderStatus.psInitializing);
if fUsesQueue then
begin
if not Assigned(fThreadLog) then
begin
fThreadLog := TThreadLog.Create;
fThreadLog.LogQueue := fLogQueue;
fThreadLog.Provider := Self;
fThreadLog.Start;
end;
end;
SetStatus(TLogProviderStatus.psRunning);
fEnabled := True;
end;
function TLogProviderBase.IsQueueable: Boolean;
begin
Result := (fUsesQueue) and (Assigned(fThreadLog));
end;
function TLogProviderBase.IsSendLimitReached(cEventType : TEventType): Boolean;
begin
Result := fSendLimits.IsLimitReached(cEventType);
if Result and Assigned(fOnSendLimits) then fOnSendLimits(fName);
end;
function TLogProviderBase.LogItemToJsonObject(cLogItem: TLogItem): TJSONObject;
var
tagName : string;
tagValue : string;
begin
Result := TJSONObject.Create;
if fJsonOutputOptions.UseUTCTime then Result.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}(fJsonOutputOptions.TimeStampName,DateTimeToJsonDate(LocalTimeToUTC(cLogItem.EventDate)))
else Result.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}(fJsonOutputOptions.TimeStampName,DateTimeToJsonDate(cLogItem.EventDate));
Result.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('type',EventTypeName[cLogItem.EventType]);
if iiHost in fIncludedInfo then Result.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('host',SystemInfo.HostName);
if iiAppName in fIncludedInfo then Result.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('application',fAppName);
if iiEnvironment in fIncludedInfo then Result.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('environment',fEnvironment);
if iiPlatform in fIncludedInfo then Result.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('platform',fPlatformInfo);
if iiOSVersion in fIncludedInfo then Result.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('OS',SystemInfo.OSVersion);
if iiUserName in fIncludedInfo then Result.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('user',SystemInfo.UserName);
if iiThreadId in IncludedInfo then Result.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('threadid',cLogItem.ThreadId.ToString);
if iiProcessId in IncludedInfo then Result.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('pid',SystemInfo.ProcessId.ToString);
if cLogItem is TLogExceptionItem then
begin
if iiExceptionInfo in fIncludedInfo then Result.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('exception',TLogExceptionItem(cLogItem).Exception);
if iiExceptionStackTrace in fIncludedInfo then Result.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('stacktrace',TLogExceptionItem(cLogItem).StackTrace);
end;
Result.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('message',cLogItem.Msg);
Result.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('level',Integer(cLogItem.EventType).ToString);
for tagName in IncludedTags do
begin
if fCustomTags.TryGetValue(tagName,tagValue) then Result.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}(tagName,tagValue);
end;
end;
function TLogProviderBase.LogItemToLine(cLogItem : TLogItem; aShowTimeStamp, aShowEventTypes : Boolean) : string;
var
tagName : string;
tagValue : string;
begin
Result := '';
if aShowTimeStamp then Result := DateTimeToStr(cLogItem.EventDate,FormatSettings);
if aShowEventTypes then Result := Format('%s [%s]',[Result,EventTypeName[cLogItem.EventType]]);
Result := Result + ' ' + cLogItem.Msg;
if iiThreadId in IncludedInfo then Result := Format('%s [ThreadId: %d]',[Result,cLogItem.ThreadId]);
if iiProcessId in IncludedInfo then Result := Format('%s [PID: %d]',[Result,SystemInfo.ProcessId]);
for tagName in IncludedTags do
begin
if fCustomTags.TryGetValue(tagName,tagValue) then Result := Format('%s [%s: %s]',[Result,tagName,tagValue]);
end;
end;
function TLogProviderBase.LogItemToJson(cLogItem: TLogItem): string;
var
json : TJSONObject;
begin
json := LogItemToJsonObject(cLogItem);
try
{$IFDEF DELPHIXE7_UP}
Result := json.ToJSON
{$ELSE}
{$IFDEF FPC}
Result := json.AsJSON;
{$ELSE}
Result := json.ToString;
{$ENDIF}
{$ENDIF}
finally
json.Free;
end;
end;
function TLogProviderBase.ResolveFormatVariable(const cToken : string; cLogItem: TLogItem) : string;
begin
//try process token as tag
if not fCustomTags.TryGetValue(cToken,Result) then
begin
//try process token as variable
if cToken = 'DATETIME' then Result := DateTimeToStr(cLogItem.EventDate,FormatSettings)
else if cToken = 'DATE' then Result := DateToStr(cLogItem.EventDate)
else if cToken = 'TIME' then Result := TimeToStr(cLogItem.EventDate)
else if cToken = 'LEVEL' then Result := cLogItem.EventTypeName
else if cToken = 'LEVELINT' then Result := Integer(cLogItem.EventType).ToString
else if cToken = 'MESSAGE' then Result := cLogItem.Msg
else if cToken = 'ENVIRONMENT' then Result := Self.Environment
else if cToken = 'PLATFORM' then Result := Self.PlatformInfo
else if cToken = 'APPNAME' then Result := Self.AppName
else if cToken = 'APPVERSION' then Result := Self.SystemInfo.AppVersion
else if cToken = 'APPPATH' then Result := Self.SystemInfo.AppPath
else if cToken = 'HOSTNAME' then Result := Self.SystemInfo.HostName
else if cToken = 'USERNAME' then Result := Self.SystemInfo.UserName
else if cToken = 'OSVERSION' then Result := Self.SystemInfo.OsVersion
else if cToken = 'CPUCORES' then Result := Self.SystemInfo.CPUCores.ToString
else if cToken = 'THREADID' then Result := cLogItem.ThreadId.ToString
else if cToken = 'PROCESSID' then Result := SystemInfo.ProcessId.ToString
else Result := '%error%';
end;
end;
{$IFDEF DELPHIXE8_UP}
function TLogProviderBase.LogItemToFormat2(cLogItem: TLogItem): string;
var
line : string;
newline : string;
token : string;
tokrep : string;
begin
if CustomFormatOutput.IsEmpty then Exit(cLogItem.Msg);
//resolve log format
Result := '';
for line in fCustomFormatOutput.Split([sLineBreak]) do
begin
newline := line;
repeat
token := GetSubString(newline,'%{','}');
if not token.IsEmpty then
begin
tokrep := ResolveFormatVariable(token.ToUpper,cLogItem);
//replace token
newline := StringReplace(newline,'%{'+token+'}',tokrep,[rfReplaceAll]);
end;
until token.IsEmpty;
Result := Result + newline;
end;
end;
{$ENDIF}
function TLogProviderBase.LogItemToFormat(cLogItem: TLogItem): string;
var
idx : Integer;
st : Integer;
et : Integer;
token : string;
begin
if CustomFormatOutput.IsEmpty then Exit(cLogItem.Msg);
//resolve log format
Result := '';
idx := 1;
st := Low(string);
et := Low(string);
while st < fCustomFormatOutput.Length do
begin
if (fCustomFormatOutput[st] = '%') and (fCustomFormatOutput[st+1] = '{') then
begin
et := st + 2;
while et < fCustomFormatOutput.Length do
begin
Inc(et);
if fCustomFormatOutput[et] = '}' then
begin
Result := Result + Copy(fCustomFormatOutput,idx,st-idx);
token := Copy(fCustomFormatOutput,st + 2,et-st-2);
Result := Result + ResolveFormatVariable(token,cLogItem);
idx := et + 1;
st := idx;
Break;
end;
end;
end
else Inc(st);
end;
if et < st then Result := Result + Copy(fCustomFormatOutput,et+1,st-et + 1);
end;
function TLogProviderBase.LogItemToHtml(cLogItem: TLogItem): string;
var
msg : TStringList;
tagName : string;
tagValue : string;
begin
msg := TStringList.Create;
try
msg.Add('<html><body>');
msg.Add(Format('<B>EventDate:</B> %s%s',[DateTimeToStr(cLogItem.EventDate,FormatSettings),HTMBR]));
msg.Add(Format('<B>Type:</B> %s%s',[EventTypeName[cLogItem.EventType],HTMBR]));
if iiAppName in IncludedInfo then msg.Add(Format('<B>Application:</B> %s%s',[SystemInfo.AppName,HTMBR]));
if iiHost in IncludedInfo then msg.Add(Format('<B>Host:</B> %s%s ',[SystemInfo.HostName,HTMBR]));
if iiUserName in IncludedInfo then msg.Add(Format('<B>User:</B> %s%s',[SystemInfo.UserName,HTMBR]));
if iiOSVersion in IncludedInfo then msg.Add(Format('<B>OS:</B> %s%s',[SystemInfo.OsVersion,HTMBR]));
if iiEnvironment in IncludedInfo then msg.Add(Format('<B>Environment:</B> %s%s',[Environment,HTMBR]));
if iiPlatform in IncludedInfo then msg.Add(Format('<B>Platform:</B> %s%s',[PlatformInfo,HTMBR]));
if iiThreadId in IncludedInfo then msg.Add(Format('<B>ThreadId:</B> %d',[cLogItem.ThreadId]));
if iiProcessId in IncludedInfo then msg.Add(Format('<B>PID:</B> %d',[SystemInfo.ProcessId]));
for tagName in IncludedTags do
begin
if fCustomTags.TryGetValue(tagName,tagValue) then msg.Add(Format('<B>%s</B> %s',[tagName,tagValue]));
end;
msg.Add(Format('<B>Message:</B> %s%s',[cLogItem.Msg,HTMBR]));
msg.Add('</body></html>');
Result := msg.Text;
finally
msg.Free;
end;
end;
function TLogProviderBase.LogItemToText(cLogItem: TLogItem): string;
var
msg : TStringList;
tagName : string;
tagValue : string;
begin
msg := TStringList.Create;
try
msg.Add(Format('EventDate: %s',[DateTimeToStr(cLogItem.EventDate,FormatSettings)]));
msg.Add(Format('Type: %s',[EventTypeName[cLogItem.EventType]]));
if iiAppName in IncludedInfo then msg.Add(Format('Application: %s',[SystemInfo.AppName]));
if iiHost in IncludedInfo then msg.Add(Format('Host: %s',[SystemInfo.HostName]));
if iiUserName in IncludedInfo then msg.Add(Format('User: %s',[SystemInfo.UserName]));
if iiOSVersion in IncludedInfo then msg.Add(Format('OS: %s',[SystemInfo.OsVersion]));
if iiEnvironment in IncludedInfo then msg.Add(Format('Environment: %s',[Environment]));
if iiPlatform in IncludedInfo then msg.Add(Format('Platform: %s',[PlatformInfo]));
if iiThreadId in IncludedInfo then msg.Add(Format('ThreadId: %d',[cLogItem.ThreadId]));
if iiProcessId in IncludedInfo then msg.Add(Format('PID: %d',[SystemInfo.ProcessId]));
for tagName in IncludedTags do
begin
if fCustomTags.TryGetValue(tagName,tagValue) then msg.Add(Format('%s: %s',[tagName,tagValue]));
end;
msg.Add(Format('Message: %s',[cLogItem.Msg]));
Result := msg.Text;
finally
msg.Free;
end;
end;
procedure TLogProviderBase.NotifyError(const aError: string);
begin
if Assigned(fOnNotifyError) then fOnNotifyError(fName,aError);
end;
procedure TLogProviderBase.Stop;
begin
if (fStatus = psStopped) or (fStatus = psStopping) then Exit;
{$IFDEF LOGGER_DEBUG}
Writeln(Format('stopping thread: %s',[Self.ClassName]));
{$ENDIF}
fEnabled := False;
SetStatus(TLogProviderStatus.psStopping);
if Assigned(fThreadLog) then
begin
if not fThreadLog.Terminated then
begin
fThreadLog.Terminate;
fThreadLog.WaitFor;
end;
fThreadLog.Free;
fThreadLog := nil;
end;
SetStatus(TLogProviderStatus.psStopped);
{$IFDEF LOGGER_DEBUG}
Writeln(Format('stopped thread: %s',[Self.ClassName]));
{$ENDIF}
end;
{$IF DEFINED(DELPHIXE7_UP)}// AND NOT DEFINED(NEXTGEN)}
function TLogProviderBase.ToJson(aIndent : Boolean = True) : string;
var
serializer : TJsonSerializer;
begin
serializer := TJsonSerializer.Create(slPublicProperty);
try
Result := serializer.ObjectToJson(Self,aIndent);
finally
serializer.Free;
end;
end;
procedure TLogProviderBase.FromJson(const aJson: string);
var
serializer : TJsonSerializer;
begin
serializer := TJsonSerializer.Create(slPublicProperty);
try
Self := TLogProviderBase(serializer.JsonToObject(Self,aJson));
if fEnabled then Self.Restart;
finally
serializer.Free;
end;
end;
procedure TLogProviderBase.SaveToFile(const aJsonFile : string);
var
json : TStringList;
begin
json := TStringList.Create;
try
json.Text := Self.ToJson;
json.SaveToFile(aJsonFile);
finally
json.Free;
end;
end;
procedure TLogProviderBase.LoadFromFile(const aJsonFile : string);
var
json : TStringList;
begin
json := TStringList.Create;
try
json.LoadFromFile(aJsonFile);
Self.FromJson(json.Text);
finally
json.Free;
end;
end;
{$ENDIF}
procedure TLogProviderBase.EnQueueItem(cLogItem : TLogItem);
begin
if fLogQueue.PushItem(cLogItem) <> TWaitResult.wrSignaled then
begin
FreeAndNil(cLogItem);
if Assigned(fOnQueueError) then fOnQueueError(Format('Logger provider "%s" insertion timeout!',[Self.ClassName]));
//raise ELogger.Create(Format('Logger provider "%s" insertion timeout!',[Self.ClassName]));
{$IFDEF LOGGER_DEBUG}
Writeln(Format('insertion timeout: %s',[Self.ClassName]));
{$ENDIF}
{$IFDEF LOGGER_DEBUG2}
end else Writeln(Format('pushitem %s (queue: %d): %s',[Self.ClassName,fLogQueue.QueueSize,cLogItem.fMsg]));
{$ELSE}
end;