-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
SimpleLog.pas
1386 lines (1197 loc) · 44.9 KB
/
SimpleLog.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
{-------------------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-------------------------------------------------------------------------------}
{===============================================================================
SimpleLog
Very simple class designed to ease logging. It can log into internal
string list, several external objects (TStrings descendants), file,
user-provided stream, or write into console if one is present.
There is also a function which allows capture of console - a log object
binds (attaches itself to) current console and captures all input and
output text that happens to be put into console via standard functions
(Write(Ln), Read(Ln)). This text is then logged as usual.
Version 1.4.1 (2024-05-03)
Last change 2024-10-04
©2012-2024 František Milt
Contacts:
František Milt: frantisek.milt@gmail.com
Support:
If you find this code useful, please consider supporting its author(s) by
making a small donation using the following link(s):
https://www.paypal.me/FMilt
Changelog:
For detailed changelog and history please refer to this git repository:
github.com/TheLazyTomcat/Lib.Simplelog
Dependencies:
AuxClasses - github.com/TheLazyTomcat/Lib.AuxClasses
* AuxExceptions - github.com/TheLazyTomcat/Lib.AuxExceptions
AuxTypes - github.com/TheLazyTomcat/Lib.AuxTypes
StrRect - github.com/TheLazyTomcat/Lib.StrRect
Library AuxExceptions is required only when rebasing local exception classes
(see symbol SimleLog_UseAuxExceptions for details).
Library AuxExceptions might also be required as an indirect dependency.
Indirect dependencies:
SimpleCPUID - github.com/TheLazyTomcat/Lib.SimpleCPUID
UInt64Utils - github.com/TheLazyTomcat/Lib.UInt64Utils
WinFileInfo - github.com/TheLazyTomcat/Lib.WinFileInfo
===============================================================================}
unit SimpleLog;
{
SimpleLog_UseAuxExceptions
If you want library-specific exceptions to be based on more advanced classes
provided by AuxExceptions library instead of basic Exception class, and don't
want to or cannot change code in this unit, you can define global symbol
SimpleLog_UseAuxExceptions to achieve this.
}
{$IF Defined(SimpleLog_UseAuxExceptions)}
{$DEFINE UseAuxExceptions}
{$IFEND}
//------------------------------------------------------------------------------
{$IF Defined(WINDOWS) or Defined(MSWINDOWS)}
{$DEFINE Windows}
{$ELSEIF Defined(LINUX) and Defined(FPC)}
{$DEFINE Linux}
{$ELSE}
{$MESSAGE FATAL 'Unsupported operating system.'}
{$IFEND}
{$IFDEF FPC}
{$MODE ObjFPC}
{$DEFINE FPC_DisableWarns}
{$MACRO ON}
{$ENDIF}
{$H+}
{$IFOPT Q+}
{$DEFINE OverflowChecks}
{$ENDIF}
interface
uses
SysUtils, Classes,
AuxTypes, AuxClasses{$IFDEF UseAuxExceptions}, AuxExceptions{$ENDIF};
{===============================================================================
Library-specific exceptions
===============================================================================}
type
ESLException = class({$IFDEF UseAuxExceptions}EAEGeneralException{$ELSE}Exception{$ENDIF});
ESLIndexOutOfBounds = class(ESLException);
ESLInvalidValue = class(ESLException);
{===============================================================================
Auxiliary routines - declaration
===============================================================================}
procedure InitFormatSettings(out FormatSettings: TFormatSettings);
{===============================================================================
--------------------------------------------------------------------------------
Console binding
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
Console binding - declaration
===============================================================================}
Function ConsoleIsBinded: Boolean;
Function ConsoleBind(const LogFileName: String): Boolean;
procedure ConsoleUnbind;
{===============================================================================
--------------------------------------------------------------------------------
TSimpleLog
--------------------------------------------------------------------------------
===============================================================================}
type
TSLLogOutput = (loInternal,loStream,loFile,loConsole,loExternals);
TSLLogOutputs = set of TSLLogOutput;
TSLSettings = record
Outputs: TSLLogOutputs;
FormatSettings: TFormatSettings;
TimeFormat: String;
TimeSeparator: String;
ForceTime: Boolean;
ForceTimeAutoreset: Boolean;
ForcedTime: TDateTime;
IndentLines: Boolean;
end;
TSLStrings = record
BreakerCharThin: Char;
BreakerCharThick: Char;
BreakerLength: Integer;
TimeStamp: String;
StartStamp: String;
EndStamp: String;
AppendStamp: String;
HeaderText: String;
end;
// TSLExternalLogItem is for internal use only.
TSLExternalLogItem = record
LogObject: TStrings;
Active: Boolean;
Owned: Boolean;
end;
{===============================================================================
TSimpleLog - class declaration
===============================================================================}
type
TSimpleLog = class(TCustomListObject)
protected
// settings and info fields
fSettings: TSLSettings;
fStrings: TSLStrings;
fTimeOfCreation: TDateTime;
fLogCounter: UInt32;
// log output fields
fInternalLog: TStringList;
fStreamLog: TStream;
fFileLog: String;
fFileLogStream: TFileStream; // only internal, do not publish
fConsolePresent: Boolean;
fExternalLogs: array of TSLExternalLogItem;
fExternalLogCount: Integer;
// console binding fields
fConsoleBinded: Boolean;
fOriginalErrOutput: TTextRec;
fOriginalOutput: TTextRec;
fOriginalInput: TTextRec;
// event/callback properties
fOnLogEvent: TStringEvent;
fOnLogCallback: TStringCallback;
// getters, setters
Function GetExternalLog(Index: Integer): TStrings; virtual;
Function GetCapacity: Integer; override;
procedure SetCapacity(Value: Integer); override;
Function GetCount: Integer; override;
procedure SetCount(Value: Integer); override;
// init/final
procedure Initialize; virtual;
procedure Finalize; virtual;
// internal logging methods
Function GetTime: TDateTime; virtual;
Function GetTimeString(Time: TDateTime): String; virtual;
Function GetIndentedString(const Str: String; IndentCount: Integer): String; virtual;
Function GetStampStr(const StampText: String; ThickBreak: Boolean): String;
procedure WriteLogToOutputs(const LogText: String; LineBreakInStreams: Boolean); virtual;
procedure ProcessConsoleLog(const LogText: String); virtual;
procedure ProcessLocalLog(const LogText: String; IndentCount: Integer = 0); virtual;
// events
procedure DoOnLog(const LogText: String); virtual;
public
constructor Create;
destructor Destroy; override;
// output setup methods
{
OutputIsActive returns true when selected output is active, false otherwise.
But note the fact that some output is active does not necessarily mean
writing to that output will be performed, there are checks done in each
write which might prevent it.
}
Function OutputIsActive(Output: TSLLogOutput): Boolean; virtual;
{
OutputActivate activates selected output method and returns its previous
state.
}
Function OutputActivate(Output: TSLLogOutput): Boolean; virtual;
Function OutputDeactivate(Output: TSLLogOutput): Boolean; virtual;
procedure SetupOutputToStream(Stream: TStream; Append: Boolean; Activate: Boolean = True); virtual;
procedure SetupOutputToFile(const FileName: String; Append: Boolean; Activate: Boolean = True); virtual;
// external logs list methods
Function LowIndex: Integer; override;
Function HighIndex: Integer; override;
Function ExternalLogLowIndex: Integer; virtual;
Function ExternalLogHighIndex: Integer; virtual;
Function ExternalLogIndexOf(LogObject: TStrings): Integer; virtual;
Function ExternalLogFind(LogObject: TStrings; out Index: Integer): Boolean; virtual;
Function ExternalLogAdd(LogObject: TStrings; Active: Boolean = True; Owned: Boolean = False): Integer; virtual;
procedure ExternalLogInsert(Index: Integer; LogObject: TStrings; Active: Boolean = True; Owned: Boolean = False); virtual;
Function ExternalLogExtract(LogObject: TStrings): TStrings; virtual;
Function ExternalLogRemove(LogObject: TStrings): Integer; virtual;
procedure ExternalLogDelete(Index: Integer); virtual;
procedure ExternalLogClear; virtual;
Function ExternalLogIsActive(Index: Integer): Boolean; virtual;
{
ExternalLogSetActive returns previous state.
}
Function ExternalLogSetActive(Index: Integer; Active: Boolean): Boolean; virtual;
Function ExternalLogIsOwned(Index: Integer): Boolean; virtual;
{
ExternalLogSetOwned returns previous state.
}
Function ExternalLogSetOwned(Index: Integer; Owned: Boolean): Boolean; virtual;
// public logging methods
Function ForceTimeSet(Time: TDateTime; Autoreset: Boolean = False): Boolean; virtual;
procedure AddLogNoTime(const LogText: String); virtual;
procedure AddLogTime(const LogText: String; Time: TDateTime); virtual;
procedure AddLog(const LogText: String); virtual;
procedure AddEmpty; virtual;
procedure AddBreaker; virtual;
procedure AddBreakerThin; virtual;
procedure AddBreakerThick; virtual;
procedure AddTimeStamp; virtual;
procedure AddStartStamp; virtual;
procedure AddEndStamp; virtual;
procedure AddAppendStamp; virtual;
procedure AddHeader; virtual;
// console binding
{
Note that if the console is binded, then output to console is disabled.
}
Function BindConsole: Boolean; virtual;
procedure UnbindConsole; virtual;
// settings properties
property Settings: TSLSettings read fSettings;
// to (de)activate individual log outputs, use methods ActivateOutput and DeactivateOutput
property Outputs: TSLLogOutputs read fSettings.Outputs write fSettings.Outputs;
property FormatSettings: TFormatSettings read fSettings.FormatSettings write fSettings.FormatSettings;
property TimeFormat: String read fSettings.TimeFormat write fSettings.TimeFormat;
property TimeSeparator: String read fSettings.TimeSeparator write fSettings.TimeSeparator;
property ForceTime: Boolean read fSettings.ForceTime write fSettings.ForceTime;
property ForceTimeAutoreset: Boolean read fSettings.ForceTimeAutoreset write fSettings.ForceTimeAutoreset;
property ForcedTime: TDateTime read fSettings.ForcedTime write fSettings.ForcedTime;
property IndentLines: Boolean read fSettings.IndentLines write fSettings.IndentLines;
// strings properties
property Strings: TSLStrings read fStrings;
property BreakerThin: Char read fStrings.BreakerCharThin write fStrings.BreakerCharThin;
property BreakerThick: Char read fStrings.BreakerCharThick write fStrings.BreakerCharThick;
property BreakerLength: Integer read fStrings.BreakerLength write fStrings.BreakerLength;
property TimeStamp: String read fStrings.TimeStamp write fStrings.TimeStamp;
property StartStamp: String read fStrings.StartStamp write fStrings.StartStamp;
property EndStamp: String read fStrings.EndStamp write fStrings.EndStamp;
property AppendStamp: String read fStrings.AppendStamp write fStrings.AppendStamp;
property HeaderText: String read fStrings.HeaderText write fStrings.HeaderText;
// informative properties
property TimeOfCreation: TDateTime read fTimeOfCreation;
property LogCounter: UInt32 read fLogCounter;
// log output properties
property InternalLog: TStringList read fInternalLog write fInternalLog;
property StreamLog: TStream read fStreamLog;
property FileLog: String read fFileLog;
property ConsolePresent: Boolean read fConsolePresent;
property ExternalLogs[Index: Integer]: TStrings read GetExternalLog; default;
property ExternalLogCount: Integer read GetCount;
property Capacity: Integer read GetCapacity; // redeclaration to make the property read-only
property Count: Integer read GetCount; // -//-
// console binding
property ConsoleBinded: Boolean read fConsoleBinded;
// events/callbacks properties
property OnLogEvent: TStringEvent read fOnLogEvent write fOnLogEvent;
property OnLogCallback: TStringCallback read fOnLogCallback write fOnLogCallback;
property OnLog: TStringEvent read fOnLogEvent write fOnLogEvent;
end;
implementation
uses
{$IFDEF Windows}Windows,{$ELSE}BaseUnix,{$ENDIF}
StrRect;
{$IFDEF FPC_DisableWarns}
{$DEFINE FPCDWM}
{$DEFINE W5024:={$WARN 5024 OFF}} // Parameter "$1" not used
{$PUSH}{$WARN 2005 OFF} // Comment level $1 found
{$IF Defined(FPC) and (FPC_FULLVERSION >= 30200)}
{$DEFINE W6058:={$WARN 6058 OFF}} // Call to subroutine "$1" marked as inline is not inlined
{$ELSE}
{$DEFINE W6058:=}
{$IFEND}
{$POP}
{$ENDIF}
{===============================================================================
Auxiliary routines - implementation
===============================================================================}
procedure InitFormatSettings(out FormatSettings: TFormatSettings);
begin
{$WARN SYMBOL_PLATFORM OFF}
{$IF not Defined(FPC) and (CompilerVersion >= 18)}
// Delphi 2006+
FormatSettings := TFormatSettings.Create(LOCALE_USER_DEFAULT);
{$ELSE}
// older delphi and FPC
{$IFDEF Windows}
// windows
{$IFDEF FPC}
FillChar(Addr(FormatSettings)^,Sizeof(TFormatSettings),0);
{$ENDIF}
GetLocaleFormatSettings(LOCALE_USER_DEFAULT,FormatSettings);
{$ELSE}
// non-windows
FormatSettings := DefaultFormatSettings;
{$ENDIF}
{$IFEND}
{$WARN SYMBOL_PLATFORM ON}
end;
{===============================================================================
--------------------------------------------------------------------------------
Console binding
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
Console binding - implementation
===============================================================================}
{-------------------------------------------------------------------------------
Console binding - internal routines
-------------------------------------------------------------------------------}
type
TSLCB_IOFunc = Function(var F: TTextRec): Integer;
const
SLCB_ERROR_SUCCESS = 0;
SLCB_ERROR_UNSUPPORTED_MODE = 10;
SLCB_ERROR_WRITE_FAILED = 11;
SLCB_ERROR_READ_FAILED = 12;
SLCB_ERROR_FLUSH_FUNC_NOT_ASSIGNED = 13;
SLCB_USERDATAINDEX_OBJECT = Low(TTextRec(nil^).UserData);
SLCB_STATUS_LOCKED = 1;
SLCB_STATUS_UNLOCKED = 0;
var
SLCB_StatusWord: Integer = SLCB_STATUS_UNLOCKED;
threadvar
SLCB_BindedLogObject: TSimpleLog;
//==============================================================================
{$IFDEF FPCDWM}{$PUSH}W6058{$ENDIF}
Function SLCB_WriteConsole(Handle: THandle; Ptr: Pointer; CharsToWrite: TStrSize; out CharsWritten: TStrSize): Boolean;
{$IFDEF Windows}
var
WrittenChars: DWORD;
begin
{$IFDEF FPC}
WrittenChars := 0;
{$ENDIF}
Result := Windows.WriteConsole(Handle,Ptr,DWORD(CharsToWrite),WrittenChars,nil);
CharsWritten := TStrSize(WrittenChars);
end;
{$ELSE}
begin
CharsWritten := TStrSize(fpWrite(cInt(Handle),Ptr^,TSize(CharsToWrite)));
Result := CharsWritten >= 0;
end;
{$ENDIF}
{$IFDEF FPCDWM}{$POP}{$ENDIF}
//------------------------------------------------------------------------------
{$IFDEF FPCDWM}{$PUSH}W6058{$ENDIF}
Function SLCB_ReadConsole(Handle: THandle; Ptr: Pointer; CharsToRead: TStrSize; out CharsRead: TStrSize): Boolean;
{$IFDEF Windows}
var
ReadChars: DWORD;
begin
{$IFDEF FPC}
ReadChars := 0;
{$ENDIF}
Result := Windows.ReadConsole(Handle,Ptr,DWORD(CharsToRead),ReadChars,nil);
CharsRead := TStrSize(ReadChars);
end;
{$ELSE}
begin
CharsRead := TStrSize(fpRead(cInt(Handle),Ptr^,TSize(CharsToRead)));
Result := CharsRead >= 0;
end;
{$ENDIF}
{$IFDEF FPCDWM}{$POP}{$ENDIF}
//==============================================================================
Function SLCB_Output(var F: TTextRec): Integer;
{
Take whatever is in the text buffer and pass it to both system call (which
will do the output into console) and simple log object stored in user data.
Note that the text buffer always consists of single-byte characters, even
when compiled with unicode.
}
var
CharsWritten: TStrSize;
ConsoleText: AnsiString;
{$IF Defined(Unicode) and Defined(Windows)} // afaik the console cannot be wide-char in linux (?? :/)
WideText: WideString;
{$IFEND}
begin
ConsoleText := '';
SetLength(ConsoleText,F.BufPos);
Move(F.Buffer,PAnsiChar(ConsoleText)^,F.BufPos);
{$IF Defined(Unicode) and Defined(Windows)}
{
Text in text buffer is single byte, but we must pass pointer to unicode text.
So copy data from text buffer into ansi string, convert it to wide string
and then pass reference to this wide string.
}
WideText := StrToWide(AnsiToStr(ConsoleText));
If SLCB_WriteConsole(F.Handle,PWideChar(WideText),Length(WideText),CharsWritten) then
begin
If CharsWritten = TStrSize(Length(WideText)) then
begin
TSimpleLog(Addr(F.UserData[SLCB_USERDATAINDEX_OBJECT])^).
ProcessConsoleLog(AnsiToStr(ConsoleText));
{$ELSE}
If SLCB_WriteConsole(F.Handle,F.BufPtr,F.BufPos,CharsWritten) then
begin
If CharsWritten = TStrSize(F.BufPos) then
begin
TSimpleLog(Addr(F.UserData[SLCB_USERDATAINDEX_OBJECT])^).
ProcessConsoleLog(CslToStr(ConsoleText));
{$IFEND}
Result := SLCB_ERROR_SUCCESS;
end
else Result := SLCB_ERROR_WRITE_FAILED;
end
else Result := SLCB_ERROR_WRITE_FAILED;
F.BufPos := 0;
end;
//------------------------------------------------------------------------------
Function SLCB_Input(var F: TTextRec): Integer;
var
CharsRead: TStrSize;
ConsoleText: AnsiString;
{$IF Defined(Unicode) and Defined(Windows)}
WideText: WideString;
begin
{
ReadConsole loads wide string, but since the text buffer accepts only
single-byte strings, it must be converted.
Note that only BufSize/2 characters is read - this is to be sure that the
converted string will fit into the text buffer.
}
SetLength(WideText,F.BufSize div 2);
If SLCB_ReadConsole(F.Handle,PWideChar(WideText),Length(WideText),CharsRead) then
begin
SetLength(WideText,CharsRead);
ConsoleText := StrToAnsi(WideToStr(WideText));
If Length(ConsoleText) <= Integer(F.BufSize) then
begin
Move(PAnsiChar(ConsoleText)^,F.Buffer,Length(ConsoleText));
TSimpleLog(Addr(F.UserData[SLCB_USERDATAINDEX_OBJECT])^).ProcessConsoleLog(WideToStr(WideText));
F.BufEnd := Length(ConsoleText);
Result := SLCB_ERROR_SUCCESS;
end
else Result := SLCB_ERROR_READ_FAILED;
end
{$ELSE}
begin
If SLCB_ReadConsole(F.Handle,F.BufPtr,F.BufSize,CharsRead) then
begin
ConsoleText := '';
SetLength(ConsoleText,CharsRead);
Move(F.Buffer,PAnsiChar(ConsoleText)^,CharsRead);
TSimpleLog(Addr(F.UserData[SLCB_USERDATAINDEX_OBJECT])^).ProcessConsoleLog(CslToStr(ConsoleText));
F.BufEnd := CharsRead;
Result := SLCB_ERROR_SUCCESS;
end
{$IFEND}
else Result := SLCB_ERROR_READ_FAILED;
F.BufPos := 0;
end;
//------------------------------------------------------------------------------
Function SLCB_Flush(var F: TTextRec): Integer;
begin
case F.Mode of
fmOutput: begin
If Assigned(F.InOutFunc) then
TSLCB_IOFunc(F.InOutFunc)(F);
Result := SLCB_ERROR_SUCCESS;
end;
fmInput: begin
F.BufPos := 0;
F.BufEnd := 0;
Result := SLCB_ERROR_SUCCESS;
end;
else
Result := SLCB_ERROR_UNSUPPORTED_MODE;
end;
end;
//------------------------------------------------------------------------------
Function SLCB_Open(var F: TTextRec): Integer;
begin
case F.Mode of
fmOutput: begin
{$IFDEF Windows}
F.Handle := GetStdHandle(STD_OUTPUT_HANDLE);
{$ELSE}
F.Handle := StdOutputHandle;
{$ENDIF}
F.InOutFunc := @SLCB_Output;
Result := SLCB_ERROR_SUCCESS;
end;
fmInput: begin
{$IFDEF Windows}
F.Handle := GetStdHandle(STD_INPUT_HANDLE);
{$ELSE}
F.Handle := StdInputHandle;
{$ENDIF}
F.InOutFunc := @SLCB_Input;
Result := SLCB_ERROR_SUCCESS;
end;
else
Result := SLCB_ERROR_UNSUPPORTED_MODE;
end;
end;
//------------------------------------------------------------------------------
Function SLCB_Close(var F: TTextRec): Integer;
begin
If Assigned(F.FlushFunc) then
Result := TSLCB_IOFunc(F.FlushFunc)(F)
else
Result := SLCB_ERROR_FLUSH_FUNC_NOT_ASSIGNED;
F.Mode := fmClosed;
end;
//------------------------------------------------------------------------------
procedure SLCB_BindLogObject(var T: Text; LogObject: TSimpleLog);
begin
with TTextRec(T) do
begin
Mode := fmClosed;
{$IFDEF FPC}
LineEnd := sLineBreak;
{$ELSE}
{$IFDEF Windows}Flags := tfCRLF{$ENDIF};
{$ENDIF}
BufSize := SizeOf(Buffer);
BufPos := 0;
BufEnd := 0;
BufPtr := @Buffer;
OpenFunc := @SLCB_Open;
FlushFunc := @SLCB_Flush;
CloseFunc := @SLCB_Close;
TSimpleLog(Addr(UserData[SLCB_USERDATAINDEX_OBJECT])^) := LogObject;
{$IF not Defined(FPC) and Defined(Windows) and Defined(Unicode)}
{
I have no idea when this field was added. But I am assuming if Delphi has
unicode support, this field is already there.
}
CodePage := CP_ACP;
{$IFEND}
Name := '';
end;
end;
{-------------------------------------------------------------------------------
Console binding - public routines
-------------------------------------------------------------------------------}
Function ConsoleIsBinded: Boolean;
begin
If Assigned(SLCB_BindedLogObject) then
Result := SLCB_BindedLogObject.ConsoleBinded
else
Result := False;
end;
//------------------------------------------------------------------------------
Function ConsoleBind(const LogFileName: String): Boolean;
var
ObjTemp: TSimpleLog;
begin
Result := False;
ObjTemp := TSimpleLog.Create;
try
ObjTemp.Outputs := [];
If ObjTemp.BindConsole then
begin
ObjTemp.SetupOutputToFile(LogFileName,False,True);
If ObjTemp.OutputIsActive(loFile) then
begin
SLCB_BindedLogObject := ObjTemp;
Result := True;
end
else FreeAndNil(ObjTemp);
end
else FreeAndNil(ObjTemp);
except
FreeAndNil(ObjTemp);
raise;
end;
end;
//------------------------------------------------------------------------------
procedure ConsoleUnbind;
begin
If Assigned(SLCB_BindedLogObject) then
FreeAndNil(SLCB_BindedLogObject); // this will automatically unbind
end;
{===============================================================================
--------------------------------------------------------------------------------
TSimpleLog
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TSimpleLog - implementation constants
===============================================================================}
const
SL_DEFSTR_TIMEFORMAT = 'yyyy-mm-dd hh:nn:ss.zzz';
SL_DEFSTR_TIMESEPARATOR = ' //: ';
SL_DEFSTR_BREAKERCHAR_THIN = '-';
SL_DEFSTR_BREAKERCHAR_THICK = '=';
SL_DEFSTR_BREAKER_LENGTH = 80;
SL_DEFSTR_TIMESTAMP = '%s';
SL_DEFSTR_STARTSTAMP = '%s - Starting log';
SL_DEFSTR_ENDSTAMP = '%s - Ending log';
SL_DEFSTR_APPENDSTAMP = '%s - Appending log';
// those plus must be there...
SL_DEFSTR_HEADERTEXT: WideString = 'SimpleLog 2.0, ' + #$00A9 + '2015-2021 Franti' + #$0161 + 'ek Milt';
{===============================================================================
TSimpleLog - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TSimpleLog - protected methods
-------------------------------------------------------------------------------}
Function TSimpleLog.GetExternalLog(Index: Integer): TStrings;
begin
If CheckIndex(Index) then
Result := fExternalLogs[Index].LogObject
else
raise ESLIndexOutOfBounds.CreateFmt('TSimpleLog.GetExternalLog: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
Function TSimpleLog.GetCapacity: Integer;
begin
Result := Length(fExternalLogs);
end;
//------------------------------------------------------------------------------
procedure TSimpleLog.SetCapacity(Value: Integer);
var
i: Integer;
begin
If Value >= 0 then
begin
If Value <> Length(fExternalLogs) then
begin
// Removing existing assigned items? If so, free owned objects.
If Value < Count then
begin
For i := Value to HighIndex do
If fExternalLogs[i].Owned then
FreeAndNil(fExternalLogs[i].LogObject);
fExternalLogCount := Value;
end;
SetLength(fExternalLogs,Value);
end;
end
else raise ESLInvalidValue.CreateFmt('TSimpleLog.SetCapacity: Invalid capacity (%d).',[Value]);
end;
//------------------------------------------------------------------------------
Function TSimpleLog.GetCount: Integer;
begin
Result := fExternalLogCount;
end;
//------------------------------------------------------------------------------
{$IFDEF FPCDWM}{$PUSH}W5024{$ENDIF}
procedure TSimpleLog.SetCount(Value: Integer);
begin
// nothing to do, count is read only
end;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
//------------------------------------------------------------------------------
procedure TSimpleLog.Initialize;
begin
// init settings
fSettings.Outputs := [loInternal];
InitFormatSettings(fSettings.FormatSettings);
fSettings.TimeFormat := SL_DEFSTR_TIMEFORMAT;
fSettings.TimeSeparator := SL_DEFSTR_TIMESEPARATOR;
fSettings.ForceTime := False;
fSettings.ForceTimeAutoreset := False;
fSettings.ForcedTime := Now;
fSettings.IndentLines := False;
// init strings
fStrings.BreakerCharThin := SL_DEFSTR_BREAKERCHAR_THIN;
fStrings.BreakerCharThick := SL_DEFSTR_BREAKERCHAR_THICK;
fStrings.BreakerLength := SL_DEFSTR_BREAKER_LENGTH;
fStrings.TimeStamp := SL_DEFSTR_TIMESTAMP;
fStrings.StartStamp := SL_DEFSTR_STARTSTAMP;
fStrings.EndStamp := SL_DEFSTR_ENDSTAMP;
fStrings.AppendStamp := SL_DEFSTR_APPENDSTAMP;
fStrings.HeaderText := WideToStr(SL_DEFSTR_HEADERTEXT);
// init other stuff
fTimeOfCreation := Now;
fLogCounter := 0;
fInternalLog := TStringList.Create;
fStreamLog := nil;
fFileLog := '';
fFileLogStream := nil;
fConsolePresent := System.IsConsole;
SetLength(fExternalLogs,0);
fExternalLogCount := 0;
fConsoleBinded := False;
fOnLogEvent := nil;
fOnLogCallback := nil;
end;
//------------------------------------------------------------------------------
procedure TSimpleLog.Finalize;
begin
fOnLogEvent := nil;
fOnLogCallback := nil;
If fConsoleBinded then
UnbindConsole;
ExternalLogClear;
// destroy internally created objects
If Assigned(fFileLogStream) then
FreeAndNil(fFileLogStream);
If Assigned(fStreamLog) then
FreeAndNil(fStreamLog);
FreeAndNil(fInternalLog);
end;
//------------------------------------------------------------------------------
Function TSimpleLog.GetTime: TDateTime;
begin
If fSettings.ForceTime then
begin
Result := fSettings.ForcedTime;
If fSettings.ForceTimeAutoreset then
fSettings.ForceTime := False;
end
else Result := Now;
end;
//------------------------------------------------------------------------------
Function TSimpleLog.GetTimeString(Time: TDateTime): String;
begin
DateTimeToString(Result,fSettings.TimeFormat,Time,fSettings.FormatSettings);
end;
//------------------------------------------------------------------------------
Function TSimpleLog.GetIndentedString(const Str: String; IndentCount: Integer): String;
procedure PutIndentation(AtPos: TStrOffset);
var
ii: TStrOffset;
begin
For ii := AtPos to Pred(AtPos + IndentCount) do
Result[ii] := ' ';
end;
var
StrPos,ResPos: TStrOffset;
ResLen: TStrSize;
begin
{
folloving are all recognized linebreak sequences:
#0
#10#13
#13#10
#10 not followed by #13
#13 not followed by #10
}
If Length(Str) > 0 then
begin
// count how long the resulting string will be for preallocation
ResLen := 0;
StrPos := 1;
while StrPos <= Length(Str) do
begin
If Ord(Str[StrPos]) in [10,13] then
begin
If StrPos < Length(Str) then
If (Ord(Str[StrPos + 1]) in [10,13]) and (Str[StrPos + 1] <> Str[StrPos]) then
begin
Inc(ResLen);
Inc(StrPos);
end;
Inc(ResLen,IndentCount + 1);
end
else If Ord(Str[StrPos]) = 0 then
Inc(ResLen,IndentCount + 1)
else
Inc(ResLen);
Inc(StrPos);
end;
Result := '';
SetLength(Result,ResLen); // preallocation
// construct the result
StrPos := 1;
ResPos := 1;
while (StrPos <= Length(Str)) and (ResPos <= Length(Result)) do
begin
If Ord(Str[StrPos]) in [10,13] then
begin
Result[ResPos] := Str[StrPos];
If StrPos < Length(Str) then
If (Ord(Str[StrPos + 1]) in [10,13]) and (Str[StrPos + 1] <> Str[StrPos]) then
begin
Inc(StrPos);
Inc(ResPos);
Result[ResPos] := Str[StrPos];
end;
PutIndentation(ResPos + 1);
Inc(ResPos,IndentCount);
end
else If Ord(Str[StrPos]) = 0 then
begin
Result[ResPos] := Str[StrPos];
PutIndentation(ResPos + 1);
Inc(ResPos,IndentCount);
end
else
Result[ResPos] := Str[StrPos];
Inc(StrPos);
Inc(ResPos);
end;
end
else Result := '';
end;
//------------------------------------------------------------------------------
Function TSimpleLog.GetStampStr(const StampText: String; ThickBreak: Boolean): String;
begin
If ThickBreak then
Result := StringOfChar(fStrings.BreakerCharThick,fStrings.BreakerLength) + sLineBreak +
StampText + sLineBreak + StringOfChar(fStrings.BreakerCharThick,fStrings.BreakerLength)
else
Result := StringOfChar(fStrings.BreakerCharThin,fStrings.BreakerLength) + sLineBreak +
StampText + sLineBreak + StringOfChar(fStrings.BreakerCharThin,fStrings.BreakerLength);
end;
//------------------------------------------------------------------------------
{$IFDEF OverflowChecks}{$Q-}{$ENDIF}
procedure TSimpleLog.WriteLogToOutputs(const LogText: String; LineBreakInStreams: Boolean);
var
i: Integer;
StreamStr: UTF8String;
begin
// write to outputs
If loInternal in fSettings.Outputs then
fInternalLog.Add(LogText);
If LineBreakInStreams then
StreamStr := StrToUTF8(LogText + sLineBreak)
else
StreamStr := StrToUTF8(LogText);
If (loStream in fSettings.Outputs) and Assigned(fStreamLog) then
fStreamLog.WriteBuffer(PUTF8Char(StreamStr)^,Length(StreamStr) * SizeOf(UTF8Char));
If (loFile in fSettings.Outputs) and Assigned(fFileLogStream) then
fFileLogStream.WriteBuffer(PUTF8Char(StreamStr)^,Length(StreamStr) * SizeOf(UTF8Char));
If (loConsole in fSettings.Outputs) and fConsolePresent and not fConsoleBinded then
WriteLn(StrToCsl(LogText));
If loExternals in fSettings.Outputs then
For i := LowIndex to HighIndex do
If fExternalLogs[i].Active then
fExternalLogs[i].LogObject.Add(LogText);
Inc(fLogCounter); // this can overflow
DoOnLog(LogText);
end;
{$IFDEF OverflowChecks}{$Q+}{$ENDIF}
//------------------------------------------------------------------------------
procedure TSimpleLog.ProcessConsoleLog(const LogText: String);
begin
WriteLogToOutputs(LogText,False);
end;
//------------------------------------------------------------------------------
procedure TSimpleLog.ProcessLocalLog(const LogText: String; IndentCount: Integer = 0);
begin
If fSettings.IndentLines and (IndentCount > 0) then
WriteLogToOutputs(GetIndentedString(LogText,IndentCount),True)
else
WriteLogToOutputs(LogText,True);
end;
//------------------------------------------------------------------------------
procedure TSimpleLog.DoOnLog(const LogText: String);
begin
If Assigned(fOnLogEvent) then
fOnLogEvent(Self,LogText)
else If Assigned(fOnLogCallback) then
fOnLogCallback(Self,LogText);
end;
{-------------------------------------------------------------------------------
TSimpleLog - public methods
-------------------------------------------------------------------------------}
constructor TSimpleLog.Create;
begin
inherited Create;
Initialize;
end;
//------------------------------------------------------------------------------
destructor TSimpleLog.Destroy;
begin
Finalize;
inherited;
end;
//------------------------------------------------------------------------------
Function TSimpleLog.OutputIsActive(Output: TSLLogOutput): Boolean;