-
Notifications
You must be signed in to change notification settings - Fork 1
/
Log4D.pas
3938 lines (3477 loc) · 118 KB
/
Log4D.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
unit Log4D;
{
Logging for Delphi.
Based on log4j Java package from Apache
(http://jakarta.apache.org/log4j/docs/index.html).
Currently based on log4j 1.2.8.
Written by Keith Wood ([email protected]).
Version 1.0 - 29 April 2001.
Version 1.2 - 9 September 2003.
Version 1.3 - 24 July 2004.
changes by adasen:
- added threshold option to TLogCustomAppender (as in SkeletonAppender.java)
- use fmShareDenyWrite instead of fmShareExclusive in TLogFileAppender
- added TLogRollingFileAppender (as in RollingFileAppender.java)
changes by mhoenemann:
- reopen a newly created file stream in TLogFileAppender to get
fmShareDenyWrite on a new logfile (due to a bug in SysUtils.FileCreate())
}
interface
{$I Defines.inc}
uses
Classes,
{$IFDEF LINUX}
SyncObjs,
{$ELSE}
Windows,
{$ENDIF}
{$IFDEF DELPHI5_UP}
Contnrs,
{$ENDIF}
SysUtils;
const
Log4DVersion = '1.2';
{ Default pattern string for log output.
Shows the application supplied message. }
DefaultPattern = '%m%n';
{ A conversion pattern equivalent to the TTCC layout.
Shows runtime, thread, level, logger, NDC, and message. }
TTCCPattern = '%r [%t] %p %c %x - %m%n';
{ Common prefix for option names in an initialisation file.
Note that the search for all option names is case sensitive. }
KeyPrefix = 'log4d';
{ Specify the additivity of a logger's appenders. }
AdditiveKey = KeyPrefix + '.additive.';
{ Define a named appender. }
AppenderKey = KeyPrefix + '.appender.';
{ Nominate a factory to use to generate loggers.
This factory must have been registered with RegisterLoggerFactory.
If none is specified, then the default factory is used. }
LoggerFactoryKey = KeyPrefix + '.loggerFactory';
{ Define a new logger, and set its logging level and appenders. }
LoggerKey = KeyPrefix + '.logger.';
{ Defining this value as true makes log4d print internal debug
statements to debug output. }
DebugKey = KeyPrefix + '.configDebug';
{ Specify the error handler to be used with an appender. }
ErrorHandlerKey = '.errorHandler';
{ Specify the filters to be used with an appender. }
FilterKey = '.filter';
{ Specify the layout to be used with an appender. }
LayoutKey = '.layout';
{ Associate an object renderer with the class to be rendered. }
RendererKey = KeyPrefix + '.renderer.';
{ Set the logging level and appenders for the root. }
RootLoggerKey = KeyPrefix + '.rootLogger';
{ Set the overall logging level. }
ThresholdKey = KeyPrefix + '.threshold';
{ Special level value signifying inherited behaviour. }
InheritedLevel = 'inherited';
{ Threshold option for TLogCustomAppender. }
ThresholdOpt = 'threshold';
{ Accept option for TLog*Filter. }
AcceptMatchOpt = 'acceptOnMatch';
{ Appending option for TLogFileAppender. }
AppendOpt = 'append';
{ Common date format option for layouts. }
DateFormatOpt = 'dateFormat';
{ File name option for TLogFileAppender. }
FileNameOpt = 'fileName';
{ Case-sensitivity option for TLogStringFilter. }
IgnoreCaseOpt = 'ignoreCase';
{ Match string option for TLogLevelMatchFilter and TLogStringFilter. }
MatchOpt = 'match';
{ Maximum string option for TLogLevelRangeFilter. }
MaxOpt = 'maximum';
{ Minimum string option for TLogLevelRangeFilter. }
MinOpt = 'minimum';
{ Pattern option for TLogPatternLayout. }
PatternOpt = 'pattern';
{ Title option for TLogHTMLLayout. }
TitleOpt = 'title';
{ Maximum file size option for TLogRollingFileAppender }
MaxFileSizeOpt = 'maxFileSize';
{ Maximum number of backup files option for TLogRollingFileAppender }
MaxBackupIndexOpt = 'maxBackupIndex';
DEFAULT_MAX_FILE_SIZE = 1*1024*1024;
DEFAULT_MAX_BACKUP_INDEX = 1;
type
{$IFDEF DELPHI4}
TClassList = TList;
TObjectList = TList;
{$ENDIF}
{$IFDEF LINUX}
TRTLCriticalSection = TCriticalSection;
{$ENDIF}
{ Log-specific exceptions. }
ELogException = class(Exception);
{ Allow for initialisation of a dynamically created object. }
ILogDynamicCreate = interface(IUnknown)
['{287DAA34-3A9F-45C6-9417-1B0D4DFAC86C}']
procedure Init;
end;
{ Get/set arbitrary options on an object. }
ILogOptionHandler = interface(ILogDynamicCreate)
['{AC1C0E30-2DBF-4C55-9C2E-9A0F1A3E4F58}']
function GetOption(const Name: string): string;
procedure SetOption(const Name, Value: string);
property Options[const Name: string]: string read GetOption write SetOption;
end;
{ Base class for handling options. }
TLogOptionHandler = class(TInterfacedObject, ILogOptionHandler)
private
FOptions: TStringList;
protected
function GetOption(const Name: string): string; virtual;
procedure SetOption(const Name, Value: string); virtual;
public
constructor Create; virtual;
destructor Destroy; override;
property Options[const Name: string]: string read GetOption write SetOption;
procedure Init; virtual;
end;
{ Levels ----------------------------------------------------------------------}
{ Levels of messages for logging.
The Level property identifies increasing severity of messages.
All those above or equal to a particular setting are logged. }
TLogLevel = class(TObject)
private
FLevel: Integer;
FName: string;
protected
constructor Create(Name: string; Level: Integer);
public
property Level: Integer read FLevel;
property Name: string read FName;
function IsGreaterOrEqual(LogLevel: TLogLevel): Boolean;
{ Retrieve a level object given its level. }
class function GetLevel(LogLevel: Integer): TLogLevel; overload;
{ Retrieve a level object given its level, or default if not valid. }
class function GetLevel(LogLevel: Integer; DefaultLevel: TLogLevel): TLogLevel;
overload;
{ Retrieve a level object given its name. }
class function GetLevel(Name: string): TLogLevel; overload;
{ Retrieve a level object given its name, or default if not valid. }
class function GetLevel(Name: string; DefaultLevel: TLogLevel): TLogLevel;
overload;
end;
const
{ Levels of logging as integer values. }
OffValue = High(Integer);
FatalValue = 50000;
ErrorValue = 40000;
WarnValue = 30000;
InfoValue = 20000;
DebugValue = 10000;
AllValue = Low(Integer);
var
{ Standard levels are automatically created (in decreasing severity):
Off, Fatal, Error, Warn, Info, Debug, All. }
Off: TLogLevel;
Fatal: TLogLevel;
Error: TLogLevel;
Warn: TLogLevel;
Info: TLogLevel;
Debug: TLogLevel;
All: TLogLevel;
{ NDC -------------------------------------------------------------------------}
type
{ Keep track of the nested diagnostic context (NDC). }
TLogNDC = class(TObject)
private
class function GetNDCIndex: Integer;
class function GetThreadId: string;
public
class procedure Clear;
class procedure CloneStack(const Context: TStringList);
class function GetDepth: Integer;
class procedure Inherit(const Context: TStringList);
class function Peek: string;
class function Pop: string;
class procedure Push(const Context: string);
class procedure Remove;
class procedure SetMaxDepth(const MaxDepth: Integer);
end;
{ Events ----------------------------------------------------------------------}
TLogLogger = class;
{ An event to be logged. }
TLogEvent = class(TPersistent)
private
FError: Exception;
FLevel: TLogLevel;
FLogger: TLogLogger;
FMessage: string;
FTimeStamp: TDateTime;
function GetElapsedTime: LongInt;
function GetErrorClass: string;
function GetErrorMessage: string;
function GetLoggerName: string;
function GetNDC: string;
function GetThreadId: LongInt;
public
constructor Create(const Logger: TLogLogger;
const Level: TLogLevel; const Message: string;
const Err: Exception; const TimeStamp: TDateTime = 0); overload;
constructor Create(const Logger: TLogLogger;
const Level: TLogLevel; const Message: TObject;
const Err: Exception; const TimeStamp: TDateTime = 0); overload;
property ElapsedTime: LongInt read GetElapsedTime;
property Error: Exception read FError;
property ErrorClass: string read GetErrorClass;
property ErrorMessage: string read GetErrorMessage;
property Level: TLogLevel read FLevel;
property LoggerName: string read GetLoggerName;
property Message: string read FMessage;
property NDC: string read GetNDC;
property ThreadId: LongInt read GetThreadId;
property TimeStamp: TDateTime read FTimeStamp;
end;
{ Logger factory --------------------------------------------------------------}
{ Factory for creating loggers. }
ILogLoggerFactory = interface(IUnknown)
['{AEE5E86C-B708-45B2-BEAD-B370D71CAA2F}']
function MakeNewLoggerInstance(const Name: string): TLogLogger;
end;
{ Default implementation of a logger factory. }
TLogDefaultLoggerFactory = class(TInterfacedObject, ILogLoggerFactory)
public
function MakeNewLoggerInstance(const Name: string): TLogLogger;
end;
{ Loggers ---------------------------------------------------------------------}
ILogAppender = interface;
ILogRenderer = interface;
TLogHierarchy = class;
{ This is the central class in the Log4D package. One of the distinctive
features of Log4D is hierarchical loggers and their evaluation. }
TLogLogger = class(TLogOptionHandler, ILogOptionHandler)
private
FAdditive: Boolean;
FAppenders: TInterfaceList;
FHierarchy: TLogHierarchy;
FLevel: TLogLevel;
FName: string;
FParent: TLogLogger;
protected
FCriticalLogger: TRTLCriticalSection;
procedure CallAppenders(const Event: TLogEvent);
procedure CloseAllAppenders;
function CountAppenders: Integer;
procedure DoLog(const LogLevel: TLogLevel; const Message: string;
const Err: Exception = nil); overload; virtual;
procedure DoLog(const LogLevel: TLogLevel; const Message: TObject;
const Err: Exception = nil); overload; virtual;
function GetLevel: TLogLevel; virtual;
public
constructor Create(const Name: string); reintroduce;
destructor Destroy; override;
property Additive: Boolean read FAdditive write FAdditive;
property Appenders: TInterfaceList read FAppenders;
property Hierarchy: TLogHierarchy read FHierarchy write FHierarchy;
property Level: TLogLevel read GetLevel write FLevel;
property Name: string read FName;
property Parent: TLogLogger read FParent;
procedure AddAppender(const Appender: ILogAppender);
procedure AssertLog(const Assertion: Boolean; const Message: string);
overload;
procedure AssertLog(const Assertion: Boolean; const Message: TObject);
overload;
procedure Debug(const Message: string; const Err: Exception = nil);
overload; virtual;
procedure Debug(const Message: TObject; const Err: Exception = nil);
overload; virtual;
procedure Error(const Message: string; const Err: Exception = nil);
overload; virtual;
procedure Error(const Message: TObject; const Err: Exception = nil);
overload; virtual;
procedure Fatal(const Message: string; const Err: Exception = nil);
overload; virtual;
procedure Fatal(const Message: TObject; const Err: Exception = nil);
overload; virtual;
function GetAppender(const Name: string): ILogAppender;
class function GetLogger(const Clazz: TClass;
const Factory: ILogLoggerFactory = nil): TLogLogger; overload;
class function GetLogger(const Name: string;
const Factory: ILogLoggerFactory = nil): TLogLogger; overload;
class function GetRootLogger: TLogLogger;
procedure Info(const Message: string; const Err: Exception = nil);
overload; virtual;
procedure Info(const Message: TObject; const Err: Exception = nil);
overload; virtual;
function IsAppender(const Appender: ILogAppender): Boolean;
function IsDebugEnabled: Boolean;
function IsEnabledFor(const LogLevel: TLogLevel): Boolean;
function IsErrorEnabled: Boolean;
function IsFatalEnabled: Boolean;
function IsInfoEnabled: Boolean;
function IsWarnEnabled: Boolean;
procedure LockLogger;
procedure Log(const LogLevel: TLogLevel; const Message: string;
const Err: Exception = nil); overload;
procedure Log(const LogLevel: TLogLevel; const Message: TObject;
const Err: Exception = nil); overload;
procedure RemoveAllAppenders;
procedure RemoveAppender(const Appender: ILogAppender); overload;
procedure RemoveAppender(const Name: string); overload;
procedure UnlockLogger;
procedure Warn(const Message: string; const Err: Exception = nil);
overload; virtual;
procedure Warn(const Message: TObject; const Err: Exception = nil);
overload; virtual;
end;
{ The specialised root logger - cannot have a nil level. }
TLogRoot = class(TLogLogger)
private
procedure SetLevel(const Level: TLogLevel);
public
constructor Create(const Level: TLogLevel);
property Level: TLogLevel read GetLevel write SetLevel;
end;
{ Specialised logger for internal logging. }
TLogLog = class(TLogLogger)
private
FInternalDebugging: Boolean;
protected
procedure DoLog(const LogLevel: TLogLevel; const Message: string;
const Err: Exception); override;
procedure DoLog(const LogLevel: TLogLevel; const Message: TObject;
const Err: Exception); override;
public
constructor Create;
property InternalDebugging: Boolean read FInternalDebugging
write FInternalDebugging;
end;
{ Hierarchy -------------------------------------------------------------------}
{ Listen to events occuring within a hierarchy. }
ILogHierarchyEventListener = interface
['{A216D50F-B9A5-4871-8EE3-CB55C41E138B}']
procedure AddAppenderEvent(const Logger: TLogLogger;
const Appender: ILogAppender);
procedure RemoveAppenderEvent(const Logger: TLogLogger;
const Appender: ILogAppender);
end;
{ This class is specialised in retreiving loggers by name and
also maintaining the logger hierarchy.
The casual user should not have to deal with this class directly.
The structure of the logger hierachy is maintained by the GetInstance
method. The hierarchy is such that children link to their parent but
parents do not have any pointers to their children. Moreover, loggers
can be instantiated in any order, in particular descendant before ancestor.
In case a descendant is created before a particular ancestor, then it creates
an empty node for the ancestor and adds itself to it. Other descendants
of the same ancestor add themselves to the previously created node. }
TLogHierarchy = class(TObject)
private
FEmittedNoAppenderWarning: Boolean;
FListeners: TInterfaceList;
FLoggers: TStringList;
FRenderedClasses: TClassList;
FRenderers: TInterfaceList;
FRoot: TLogLogger;
FThreshold: TLogLevel;
procedure SetThresholdProp(const Level: TLogLevel);
procedure UpdateParent(const Logger: TLogLogger);
protected
FCriticalHierarchy: TRTLCriticalSection;
public
constructor Create(Root: TLogLogger);
destructor Destroy; override;
property Root: TLogLogger read FRoot;
property Threshold: TLogLevel read FThreshold write SetThresholdProp;
procedure AddHierarchyEventListener(
const Listener: ILogHierarchyEventListener);
procedure AddRenderer(RenderedClass: TClass; Renderer: ILogRenderer);
procedure Clear;
procedure EmitNoAppenderWarning(const Logger: TLogLogger);
function Exists(const Name: string): TLogLogger;
procedure FireAppenderEvent(const Adding: Boolean; const Logger: TLogLogger;
const Appender: ILogAppender);
procedure GetCurrentLoggers(const List: TStringList);
function GetLogger(const Name: string;
const Factory: ILogLoggerFactory = nil): TLogLogger;
function GetRenderer(const RenderedClass: TClass): ILogRenderer;
function IsDisabled(const LogLevel: Integer): Boolean;
procedure RemoveHierarchyEventListener(
const Listener: ILogHierarchyEventListener);
procedure ResetConfiguration;
procedure SetThreshold(const Name: string);
procedure Shutdown;
end;
{ Layouts ---------------------------------------------------------------------}
{ Functional requirements for a layout. }
ILogLayout = interface(ILogOptionHandler)
['{87FDD680-96D7-45A0-A135-CB88ABAD5519}']
function Format(const Event: TLogEvent): string;
function GetContentType: string;
function GetFooter: string;
function GetHeader: string;
function IgnoresException: Boolean;
property ContentType: string read GetContentType;
property Footer: string read GetFooter;
property Header: string read GetHeader;
end;
{ Abstract base for layouts.
Subclasses must at least override Format.
Accepts the following options:
# Format for date and time stamps, string, optional, defaults to ShortDateFormat
# See FormatDateTime function for more details
log4d.appender.<name>.layout.dateFormat=yyyy/mm/dd hh:nn:ss.zzz
}
TLogCustomLayout = class(TLogOptionHandler, ILogDynamicCreate,
ILogOptionHandler, ILogLayout)
private
FDateFormat: string;
protected
property DateFormat: string read FDateFormat write FDateFormat;
function GetContentType: string; virtual;
function GetHeader: string; virtual;
function GetFooter: string; virtual;
procedure SetOption(const Name, Value: string); override;
public
property ContentType: string read GetContentType;
property Footer: string read GetFooter;
property Header: string read GetHeader;
function Format(const Event: TLogEvent): string; virtual; abstract;
function IgnoresException: Boolean; virtual;
procedure Init; override;
end;
{ Basic implementation of a layout. }
TLogSimpleLayout = class(TLogCustomLayout)
public
function Format(const Event: TLogEvent): string; override;
end;
{ This layout outputs events in a HTML table.
Accepts the following options:
# Title for HTML page, string, optional
log4d.appender.<name>.layout.title=Logging Messages
}
TLogHTMLLayout = class(TLogCustomLayout)
private
FTitle: string;
protected
function GetContentType: string; override;
function GetFooter: string; override;
function GetHeader: string; override;
procedure SetOption(const Name, Value: string); override;
public
property Title: string read FTitle write FTitle;
function Format(const Event: TLogEvent): string; override;
function IgnoresException: Boolean; override;
end;
{ Layout based on specified pattern.
Accepts the following options:
# Format for rendering the log event, string, optional, defaults to %m%n
# See comments of Format method for more details
log4d.appender.<name>.layout.pattern=%r [%t] %p %c %x - %m%n
}
TLogPatternLayout = class(TLogCustomLayout)
private
FPattern: string;
FPatternParts: TStringList;
procedure SetPattern(const Pattern: string);
protected
procedure SetOption(const Name, Value: string); override;
public
constructor Create(const Pattern: string = DefaultPattern); reintroduce;
destructor Destroy; override;
property Pattern: string read FPattern write SetPattern;
function Format(const Event: TLogEvent): string; override;
procedure Init; override;
end;
{ Renderers -------------------------------------------------------------------}
{ Renderers transform an object into a string message for display. }
ILogRenderer = interface(ILogOptionHandler)
['{169B03C6-E2C7-4F62-AD19-17408AB30681}']
function Render(const Message: TObject): string;
end;
{ Abstract base class for renderers - handles basic option setting.
Subclasses must at least override Render. }
TLogCustomRenderer = class(TLogOptionHandler, ILogDynamicCreate,
ILogOptionHandler, ILogRenderer)
public
function Render(const Message: TObject): string; virtual; abstract;
end;
{ ErrorHandler ----------------------------------------------------------------}
{ Appenders may delegate their error handling to ErrorHandlers.
Error handling is a particularly tedious to get right because by
definition errors are hard to predict and to reproduce. }
ILogErrorHandler = interface(ILogOptionHandler)
['{B902C52A-5E4E-47A8-B291-BE8E7660F754}']
procedure SetAppender(const Appender: ILogAppender);
procedure SetBackupAppender(const BackupAppender: ILogAppender);
procedure SetLogger(const Logger: TLogLogger);
{ The appender for which errors are handled. }
property Appender: ILogAppender write SetAppender;
{ The appender to use in case of failure. }
property BackupAppender: ILogAppender write SetBackupAppender;
{ The logger that the failing appender might be attached to. }
property Logger: TLogLogger write SetLogger;
{ This method prints the error message passed as a parameter. }
procedure Error(const Message: string); overload;
{ This method should handle the error. Information about the error
condition is passed a parameter. }
procedure Error(const Message: string; const Err: Exception;
const ErrorCode: Integer; const Event: TLogEvent = nil); overload;
end;
{ Abstract base class for error handlers - handles basic option setting.
Subclasses must at least override Error. }
TLogCustomErrorHandler = class(TLogOptionHandler, ILogDynamicCreate,
ILogOptionHandler, ILogErrorHandler)
private
FAppender: ILogAppender;
FBackupAppender: ILogAppender;
FLogger: TLogLogger;
protected
procedure SetAppender(const Appender: ILogAppender); virtual;
procedure SetBackupAppender(const BackupAppender: ILogAppender); virtual;
procedure SetLogger(const Logger: TLogLogger); virtual;
public
property Appender: ILogAppender write SetAppender;
property BackupAppender: ILogAppender write SetBackupAppender;
property Logger: TLogLogger write SetLogger;
procedure Error(const Message: string); overload; virtual; abstract;
procedure Error(const Message: string; const Err: Exception;
const ErrorCode: Integer; const Event: TLogEvent = nil); overload;
virtual; abstract;
end;
{ Fallback on an alternative appender if an error arises. }
TLogFallbackErrorHandler = class(TLogCustomErrorHandler)
private
FLoggers: TObjectList;
protected
procedure SetLogger(const Logger: TLogLogger); override;
public
constructor Create; override;
destructor Destroy; override;
procedure Error(const Message: string); overload; override;
procedure Error(const Message: string; const Err: Exception;
const ErrorCode: Integer; const Event: TLogEvent = nil); overload;
override;
end;
{ Displays only the first error sent to it to debugging output. }
TLogOnlyOnceErrorHandler = class(TLogCustomErrorHandler)
private
FSeenError: Boolean;
public
procedure Error(const Message: string); overload; override;
procedure Error(const Message: string; const Err: Exception;
const ErrorCode: Integer; const Event: TLogEvent = nil); overload;
override;
end;
{ Filters ---------------------------------------------------------------------}
TLogFilterDecision = (fdDeny, fdNeutral, fdAccept);
{ Filters can control to a finer degree of detail which messages get logged. }
ILogFilter = interface(ILogOptionHandler)
['{B28213D7-ACE2-4C44-B820-D9437D44F8DA}']
function Decide(const Event: TLogEvent): TLogFilterDecision;
end;
{ Abstract base class for filters - handles basic option setting.
Subclasses must at least override Decide.
Accepts the following options:
# Class identification
log4d.appender.<name>.filter1=TLogCustomFilter
# Accept or reject the log event when deciding, Boolean, optional, default true
log4d.appender.<name>.filter1.acceptOnMatch=true
}
TLogCustomFilter = class(TLogOptionHandler, ILogDynamicCreate,
ILogOptionHandler, ILogFilter)
private
FAcceptOnMatch: Boolean;
protected
property AcceptOnMatch: Boolean read FAcceptOnMatch write FAcceptOnMatch;
procedure SetOption(const Name, Value: string); override;
public
constructor Create(const AcceptOnMatch: Boolean = True); reintroduce;
function Decide(const Event: TLogEvent): TLogFilterDecision; virtual;
abstract;
end;
{ Deny all messages. }
TLogDenyAllFilter = class(TLogCustomFilter)
public
property AcceptOnMatch;
function Decide(const Event: TLogEvent): TLogFilterDecision; override;
end;
{ Filter by the message's level.
Accepts the following options (as well as the standard acceptOnMatch one):
# Class identification
log4d.appender.<name>.filter1=TLogLevelMatchFilter
# Logging level to match on, Level, mandatory
log4d.appender.<name>.filter1.match=warn
}
TLogLevelMatchFilter = class(TLogCustomFilter)
private
FMatchLevel: TLogLevel;
protected
procedure SetOption(const Name, Value: string); override;
public
constructor Create(const MatchLevel: TLogLevel;
const AcceptOnMatch: Boolean = True); reintroduce;
property AcceptOnMatch;
property MatchLevel: TLogLevel read FMatchLevel write FMatchLevel;
function Decide(const Event: TLogEvent): TLogFilterDecision; override;
end;
{ Filter by the message's level being within a range.
Accepts the following options (as well as the standard acceptOnMatch one):
# Class identification
log4d.appender.<name>.filter1=TLogLevelRangeFilter
# Minimum logging level to match on, Level, mandatory
log4d.appender.<name>.filter1.minimum=warn
# Maximum logging level to match on, Level, mandatory
log4d.appender.<name>.filter1.maximum=error
}
TLogLevelRangeFilter = class(TLogCustomFilter)
private
FMaxLevel: TLogLevel;
FMinLevel: TLogLevel;
protected
procedure SetOption(const Name, Value: string); override;
public
constructor Create(const MaxLevel, MinLevel: TLogLevel;
const AcceptOnMatch: Boolean = True); reintroduce;
property AcceptOnMatch;
property MaxLevel: TLogLevel read FMaxLevel write FMaxLevel;
property MinLevel: TLogLevel read FMinLevel write FMinLevel;
function Decide(const Event: TLogEvent): TLogFilterDecision; override;
end;
{ Filter by text within the message.
Accepts the following options (as well as the standard acceptOnMatch one):
# Class identification
log4d.appender.<name>.filter1=TLogStringFilter
# Text to match on anywhere in message, string, mandatory
log4d.appender.<name>.filter1.match=xyz
# Whether match is case-sensitive, Boolean, optional, defaults to false
log4d.appender.<name>.filter1.ignoreCase=true
}
TLogStringFilter = class(TLogCustomFilter)
private
FIgnoreCase: Boolean;
FMatch: string;
protected
procedure SetOption(const Name, Value: string); override;
public
constructor Create(const Match: string; const IgnoreCase: Boolean = False;
const AcceptOnMatch: Boolean = True); reintroduce;
property AcceptOnMatch;
property IgnoreCase: Boolean read FIgnoreCase write FIgnoreCase;
property Match: string read FMatch write FMatch;
function Decide(const Event: TLogEvent): TLogFilterDecision; override;
end;
{ Appenders -------------------------------------------------------------------}
{ Implement this interface for your own strategies
for printing log statements. }
ILogAppender = interface(ILogOptionHandler)
['{E1A06EA7-34CA-4DA4-9A8A-C76CF34257AC}']
procedure AddFilter(const Filter: ILogFilter);
procedure Append(const Event: TLogEvent);
procedure Close;
function GetErrorHandler: ILogErrorHandler;
function GetFilters: TInterfaceList;
function GetLayout: ILogLayout;
function GetName: string;
procedure RemoveAllFilters;
procedure RemoveFilter(const Filter: ILogFilter);
function RequiresLayout: Boolean;
procedure SetErrorHandler(const ErrorHandler: ILogErrorHandler);
procedure SetLayout(const Layout: ILogLayout);
procedure SetName(const Name: string);
property ErrorHandler: ILogErrorHandler read GetErrorHandler
write SetErrorHandler;
property Filters: TInterfaceList read GetFilters;
property Layout: ILogLayout read GetLayout write SetLayout;
property Name: string read GetName write SetName;
end;
{ Basic implementation of an appender for printing log statements.
Subclasses should at least override DoAppend(string). }
TLogCustomAppender = class(TLogOptionHandler, ILogDynamicCreate,
ILogOptionHandler, ILogAppender)
private
FClosed: Boolean;
FErrorHandler: ILogErrorHandler;
FFilters: TInterfaceList;
FLayout: ILogLayout;
FName: string;
FThreshold : TLogLevel;
function GetErrorHandler: ILogErrorHandler;
function GetFilters: TInterfaceList;
function GetLayout: ILogLayout;
function GetName: string;
procedure SetErrorHandler(const ErrorHandler: ILogErrorHandler);
procedure SetLayout(const Layout: ILogLayout);
procedure SetName(const Name: string);
protected
FCriticalAppender: TRTLCriticalSection;
function CheckEntryConditions: Boolean; virtual;
function CheckFilters(const Event: TLogEvent): Boolean; virtual;
procedure DoAppend(const Event: TLogEvent); overload; virtual;
procedure DoAppend(const Message: string); overload; virtual; abstract;
procedure WriteFooter; virtual;
procedure WriteHeader; virtual;
procedure SetOption(const Name, Value: string); override;
function isAsSevereAsThreshold(level : TLogLevel) : boolean;
public
constructor Create(const Name: string; const Layout: ILogLayout = nil);
reintroduce; virtual;
destructor Destroy; override;
property ErrorHandler: ILogErrorHandler read GetErrorHandler
write SetErrorHandler;
property Filters: TInterfaceList read GetFilters;
property Layout: ILogLayout read GetLayout write SetLayout;
property Name: string read GetName write SetName;
procedure AddFilter(const Filter: ILogFilter); virtual;
procedure Append(const Event: TLogEvent); virtual;
procedure Close; virtual;
procedure Init; override;
procedure RemoveAllFilters; virtual;
procedure RemoveFilter(const Filter: ILogFilter); virtual;
function RequiresLayout: Boolean; virtual;
end;
{ Discard log messages. }
TLogNullAppender = class(TLogCustomAppender)
protected
procedure DoAppend(const Message: string); override;
end;
{ Send log messages to debugging output. }
TLogODSAppender = class(TLogCustomAppender)
protected
procedure DoAppend(const Message: string); override;
end;
{ Send log messages to a stream. }
TLogStreamAppender = class(TLogCustomAppender)
private
FStream: TStream;
protected
procedure DoAppend(const Message: string); override;
public
constructor Create(const Name: string; const Stream: TStream;
const Layout: ILogLayout = nil); reintroduce; virtual;
destructor Destroy; override;
end;
{ Send log messages to a file.
Accepts the following options:
# Class identification
log4d.appender.<name>=TLogFileAppender
# Name of the file to write to, string, mandatory
log4d.appender.<name>.fileName=C:\Logs\App.log
# Whether to append to file, Boolean, optional, defaults to true
log4d.appender.<name>.append=false
}
TLogFileAppender = class(TLogStreamAppender)
private
FAppend: Boolean;
FFileName: TFileName;
protected
procedure SetOption(const Name, Value: string); override;
procedure SetLogFile(const Name: string);
procedure CloseLogFile;
public
constructor Create(const Name, FileName: string;
const Layout: ILogLayout = nil; const Append: Boolean = True);
reintroduce; virtual;
property FileName: TFileName read FFileName;
property OpenAppend: Boolean read FAppend;
end;
{ Send log messages to a file which uses logfile rotation
Accepts the following options:
# Class identification
log4d.appender.<name>=TLogRollingFileAppender
# Name of the file to write to, string, mandatory
log4d.appender.<name>.fileName=C:\Logs\App.log
# Whether to append to file, Boolean, optional, defaults to true
log4d.appender.<name>.append=false
# Max. file size accepts suffix "KB", "MB" and "GB", optional, default 10MB
log4d.appender.<name>.maxFileSize=10MB
# Max number of backup files, optional, default is 1
log4d.appender.<name>.maxBackupIndex=3
}
TLogRollingFileAppender = class(TLogFileAppender)
private
FMaxFileSize : integer;
FMaxBackupIndex : integer;
FCurrentSize : integer;
protected
procedure SetOption(const Name, Value: string); override;
procedure DoAppend(const msg: string); override;
procedure RollOver; virtual; // just in case someone wants to override it...
public
procedure Init; override;
property MaxFileSize : integer read FMaxFileSize;
property MaxBackupIndex : integer read FMaxBackupIndex;
end;
{ Configurators ---------------------------------------------------------------}
{ Use this class to quickly configure the package. }
TLogBasicConfigurator = class(TObject)
private
FRegistry: TStringList;
FLoggerFactory: ILogLoggerFactory;
protected
{ Used by subclasses to add a renderer
to the hierarchy passed as parameter. }
procedure AddRenderer(const Hierarchy: TLogHierarchy;
const RenderedName, RendererName: string);
function AppenderGet(const Name: string): ILogAppender;
procedure AppenderPut(const Appender: ILogAppender);
procedure SetGlobalProps(const Hierarchy: TLogHierarchy;
const FactoryClassName, Debug, Threshold: string);
public
constructor Create;
destructor Destroy; override;
{ Add appender to the root logger. If no appender is provided,
add a TLogODSAppender that uses TLogPatternLayout with the
TTCCPattern and prints to debugging output for the root logger. }
class procedure Configure(const Appender: ILogAppender = nil);
{ Reset the default hierarchy to its default. It is equivalent to calling
Logger.GetDefaultHierarchy.ResetConfiguration.
See TLogHierarchy.ResetConfiguration for more details. }
class procedure ResetConfiguration;
end;
{ Extends BasicConfigurator to provide configuration from an external file.
See DoConfigure for the expected format.
It is sometimes useful to see how Log4D is reading configuration files.
You can enable Log4D internal logging by defining the log4d.debug variable. }
TLogPropertyConfigurator = class(TLogBasicConfigurator)
protected
procedure ConfigureRootLogger(const Props: TStringList;
const Hierarchy: TLogHierarchy);
procedure ParseAdditivityForLogger(const Props: TStringList;
const Logger: TLogLogger);
function ParseAppender(const Props: TStringList;
const AppenderName: string): ILogAppender;
procedure ParseLoggersAndRenderers(const Props: TStringList;
const Hierarchy: TLogHierarchy);
procedure ParseLogger(const Props: TStringList; const Logger: TLogLogger;
const Value: string);
public
class procedure Configure(const Filename: string); overload;
class procedure Configure(const Props: TStringList); overload;
procedure DoConfigure(const FileName: string;
const Hierarchy: TLogHierarchy); overload;
procedure DoConfigure(const Props: TStringList;
const Hierarchy: TLogHierarchy); overload;
end;
{ Register a new appender class. }
procedure RegisterAppender(const Appender: TClass);
{ Find an appender based on its class name and create a new instance of it. }
function FindAppender(const ClassName: string): ILogAppender;
{ Register a new logger factory class. }
procedure RegisterLoggerFactory(const LoggerFactory: TClass);
{ Find a logger factory based on its class name
and create a new instance of it. }
function FindLoggerFactory(const ClassName: string): ILogLoggerFactory;
{ Register a new error handler class. }
procedure RegisterErrorHandler(const ErrorHandler: TClass);
{ Find an error handler based on its class name
and create a new instance of it. }
function FindErrorHandler(const ClassName: string): ILogErrorHandler;
{ Register a new filter class. }
procedure RegisterFilter(const Filter: TClass);
{ Find a filter based on its class name and create a new instance of it. }
function FindFilter(const ClassName: string): ILogFilter;
{ Register a new layout class. }
procedure RegisterLayout(const Layout: TClass);
{ Find a layout based on its class name and create a new instance of it. }
function FindLayout(const ClassName: string): ILogLayout;
{ Register a new class that can be rendered. }
procedure RegisterRendered(const Rendered: TClass);
{ Find a rendered class based on its class name and return its class. }
function FindRendered(const ClassName: string): TClass;
{ Register a new object renderer class. }
procedure RegisterRenderer(const Renderer: TClass);
{ Find an object renderer based on its class name
and create a new instance of it. }
function FindRenderer(const ClassName: string): ILogRenderer;
{ Convert string value to a Boolean, with default. }
function StrToBool(Value: string; const Default: Boolean): Boolean;
{$IFDEF LINUX}
procedure EnterCriticalSection(var CS: TCriticalSection);
procedure LeaveCriticalSection(var CS: TCriticalSection);
procedure InitializeCriticalSection(var CS: TCriticalSection);
procedure DeleteCriticalSection(var CS: TCriticalSection);
function GetCurrentThreadID: Integer;
procedure OutputDebugString(const S: PChar);
{$ENDIF}
var
{ Default implementation of ILogLoggerFactory }
DefaultLoggerFactory: TLogDefaultLoggerFactory;