File: lazlogger.pas

package info (click to toggle)
lazarus 2.0.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 214,460 kB
  • sloc: pascal: 1,862,622; xml: 265,709; cpp: 56,595; sh: 3,008; java: 609; makefile: 535; perl: 297; sql: 222; ansic: 137
file content (879 lines) | stat: -rw-r--r-- 22,290 bytes parent folder | download | duplicates (2)
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
{
 *****************************************************************************
  This file is part of LazUtils.

  See the file COPYING.modifiedLGPL.txt, included in this distribution,
  for details about the license.
 *****************************************************************************
}
unit LazLogger;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, types, math,
  // LazUtils
  LazLoggerBase, LazClasses, LazFileUtils, LazStringUtils, LazUTF8;

type

  PLazLoggerLogGroup = LazLoggerBase.PLazLoggerLogGroup;

{$DEFINE USED_BY_LAZLOGGER}
{$I LazLoggerIntf.inc}


function DbgStr(const StringWithSpecialChars: string): string; overload;
function DbgStr(const StringWithSpecialChars: string; StartPos, Len: PtrInt): string; overload;
function DbgStr(const p: PChar; Len: PtrInt): string; overload;
function DbgWideStr(const StringWithSpecialChars: widestring): string; overload;

type

  { TLazLoggerFileHandle }

  TLazLoggerFileHandle = class
  private
    FActiveLogText: PText; // may point to stdout
    FCloseLogFileBetweenWrites: Boolean;
    FLastWriteFailed: Boolean;
    FLogName: String;
    FLogText: Text;
    FLogTextInUse, FLogTextFailed: Boolean;
    FUseStdOut: Boolean;
    FWriteFailedCount: Integer;
    procedure DoOpenFile;
    procedure DoCloseFile;
    function GetWriteTarget: TLazLoggerWriteTarget;
    procedure SetCloseLogFileBetweenWrites(AValue: Boolean);
    procedure SetLogName(AValue: String);
  public
    constructor Create;
    destructor Destroy; override;
    procedure OpenFile;
    procedure CloseFile;
    procedure ResetWriteFailedCounter;

    procedure WriteToFile(const s: string); virtual;
    procedure WriteLnToFile(const s: string); virtual;

    property  LogName: String read FLogName write SetLogName;
    property  UseStdOut: Boolean read FUseStdOut write FUseStdOut;
    property  CloseLogFileBetweenWrites: Boolean read FCloseLogFileBetweenWrites write SetCloseLogFileBetweenWrites;
    property  WriteTarget: TLazLoggerWriteTarget read GetWriteTarget;
    property  ActiveLogText: PText read FActiveLogText;
    property  WriteFailedCount: Integer read FWriteFailedCount;
    property  LastWriteFailed: Boolean read FLastWriteFailed;
  end;

  { TLazLoggerFileHandleThreadSave
    file operations in critical section
  }

  TLazLoggerFileHandleThreadSave = class (TLazLoggerFileHandle)
  private
    FWriteToFileLock: TRTLCriticalSection;
  public
    constructor Create;
    destructor Destroy; override;
    procedure WriteToFile(const s: string); override;
    procedure WriteLnToFile(const s: string); override;
  end;

  { TLazLoggerFileHandleMainThread
    file operations queued for main thread
  }

  TLazLoggerFileHandleMainThread = class (TLazLoggerFileHandle)
  private
  type
    PWriteListEntry = ^TWriteListEntry;
    TWriteListEntry = record
      Next: PWriteListEntry;
      Data: String;
      Ln: Boolean;
    end;
  private
    FWriteToFileLock: TRTLCriticalSection;
    FFirst, FLast: PWriteListEntry;

    procedure MainThreadWrite;
  public
    constructor Create;
    destructor Destroy; override;
    procedure WriteToFile(const s: string); override;
    procedure WriteLnToFile(const s: string); override;
  end;


  { TLazLoggerFile }

  TLazLoggerFile = class(TLazLoggerWithGroupParam)
  private
    FFileHandle: TLazLoggerFileHandle;
    FOnDbgOut: TLazLoggerWriteEvent;
    FOnDebugLn: TLazLoggerWriteEvent;
    FBlockHandler: TList;


    FEnvironmentForLogFileName: String;
    //FLogName: String;

    FParamForLogFileName: String;
    FGetLogFileNameDone: Boolean;

    FIndentCriticalSection: TRTLCriticalSection;
    FDebugNestLvl: Integer;
    FDebugIndent: String;
    FDebugNestAtBOL: Boolean;

    function  GetFileHandle: TLazLoggerFileHandle;
    procedure SetEnvironmentForLogFileName(AValue: String);
    procedure SetFileHandle(AValue: TLazLoggerFileHandle);
    procedure SetParamForLogFileName(AValue: String);
    function  GetLogFileName: string;
  private
    // forward to TLazLoggerFileHandle
    function  GetCloseLogFileBetweenWrites: Boolean;
    function  GetLogName: String;
    function  GetUseStdOut: Boolean;
    procedure SetCloseLogFileBetweenWrites(AValue: Boolean);
    procedure SetLogName(AValue: String);
    procedure SetUseStdOut(AValue: Boolean);
  protected
    procedure DoInit; override;
    procedure DoFinsh; override;

    procedure IncreaseIndent; overload; override;
    procedure DecreaseIndent; overload; override;
    procedure IncreaseIndent(LogGroup: PLazLoggerLogGroup); overload; override;
    procedure DecreaseIndent(LogGroup: PLazLoggerLogGroup); overload; override;
    procedure IndentChanged; override;
    procedure CreateIndent; virtual;
    function GetBlockHandler(AIndex: Integer): TLazLoggerBlockHandler; override;
    procedure ClearAllBlockHandler;


    procedure DoDbgOut(const s: string); override;
    procedure DoDebugLn(const s: string); override;
    procedure DoDebuglnStack(const s: string); override;

    property FileHandle: TLazLoggerFileHandle read GetFileHandle write SetFileHandle;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Assign(Src: TLazLogger); override;
    function CurrentIndentLevel: Integer; override;
    // A param on the commandline, that may contain the name (if not already set)
    // example/default: --debug-log=
    property  ParamForLogFileName: String read FParamForLogFileName write SetParamForLogFileName;
    // Environment variable used to specify log file name 
    // * is replaced by param(0) - the application name without extension
    // example/default: *_debuglog
    property  EnvironmentForLogFileName: String read FEnvironmentForLogFileName write SetEnvironmentForLogFileName; 

    property  OnDebugLn: TLazLoggerWriteEvent read FOnDebugLn write FOnDebugLn;
    property  OnDbgOut:  TLazLoggerWriteEvent read FOnDbgOut write FOnDbgOut;

    procedure AddBlockHandler(AHandler: TLazLoggerBlockHandler); override;
    procedure RemoveBlockHandler(AHandler: TLazLoggerBlockHandler); override;
    function BlockHandlerCount: Integer; override;

    // forward to TLazLoggerFileHandle
    property  LogName: String read GetLogName write SetLogName;
    property  UseStdOut: Boolean read GetUseStdOut write SetUseStdOut;
    property  CloseLogFileBetweenWrites: Boolean read GetCloseLogFileBetweenWrites write SetCloseLogFileBetweenWrites;
  end;

function GetDebugLogger: TLazLoggerFile; inline;
procedure SetDebugLogger(ALogger: TLazLoggerFile);

property DebugLogger: TLazLoggerFile read GetDebugLogger write SetDebugLogger;

implementation

{$I LazLoggerImpl.inc}

{$ifdef wince}
const
  Str_LCL_Debug_File = 'lcldebug.log';
{$endif}

(* Creation / Access *)

function CreateDebugLogger: TRefCountedObject;
begin
  Result := TLazLoggerFile.Create;
  TLazLoggerFile(Result).Assign(GetExistingDebugLogger);
end;

function GetDebugLogger: TLazLoggerFile; inline;
begin
  Result := TLazLoggerFile(LazLoggerBase.DebugLogger);
end;

procedure SetDebugLogger(ALogger: TLazLoggerFile);
begin
  LazLoggerBase.DebugLogger := ALogger;
end;

{ TLazLoggerFileHandleMainThread }

procedure TLazLoggerFileHandleMainThread.MainThreadWrite;
var
  Data, NextData: PWriteListEntry;
begin
  EnterCriticalsection(FWriteToFileLock);
  try
    Data := FFirst;
    FFirst := nil;
    FLast := nil;
  finally
    LeaveCriticalsection(FWriteToFileLock);
  end;

  while Data <> nil do begin
    NextData := Data^.Next;
    if Data^.Ln
    then inherited WriteLnToFile(Data^.Data)
    else inherited WriteToFile(Data^.Data);
    Dispose(Data);
    Data := NextData;
  end;
end;

constructor TLazLoggerFileHandleMainThread.Create;
begin
  InitCriticalSection(FWriteToFileLock);
  inherited;
end;

destructor TLazLoggerFileHandleMainThread.Destroy;
begin
  inherited Destroy;
  DoneCriticalsection(FWriteToFileLock);
end;

procedure TLazLoggerFileHandleMainThread.WriteToFile(const s: string);
var
  Data: PWriteListEntry;
begin
  New(Data);
  Data^.Data := s;
  Data^.Ln := False;
  Data^.Next := nil;
  EnterCriticalsection(FWriteToFileLock);
  try
    if FLast = nil then
      FFirst := Data
    else
      FLast^.Next := Data;
    FLast := Data;
  finally
    LeaveCriticalsection(FWriteToFileLock);
  end;
  TThread.Queue(nil, @MainThreadWrite);
end;

procedure TLazLoggerFileHandleMainThread.WriteLnToFile(const s: string);
var
  Data: PWriteListEntry;
begin
  New(Data);
  Data^.Data := s;
  Data^.Ln := True;
  Data^.Next := nil;
  EnterCriticalsection(FWriteToFileLock);
  try
    if FLast = nil then
      FFirst := Data
    else
      FLast^.Next := Data;
    FLast := Data;
  finally
    LeaveCriticalsection(FWriteToFileLock);
  end;
  TThread.Queue(nil, @MainThreadWrite);
end;

{ TLazLoggerFileHandleThreadSave }

constructor TLazLoggerFileHandleThreadSave.Create;
begin
  InitCriticalSection(FWriteToFileLock);
  inherited;
end;

destructor TLazLoggerFileHandleThreadSave.Destroy;
begin
  inherited Destroy;
  DoneCriticalsection(FWriteToFileLock);
end;

procedure TLazLoggerFileHandleThreadSave.WriteToFile(const s: string);
begin
  EnterCriticalsection(FWriteToFileLock);
  try
    inherited WriteToFile(s);
  finally
    LeaveCriticalsection(FWriteToFileLock);
  end;
end;

procedure TLazLoggerFileHandleThreadSave.WriteLnToFile(const s: string);
begin
  EnterCriticalsection(FWriteToFileLock);
  try
    inherited WriteLnToFile(s);
  finally
    LeaveCriticalsection(FWriteToFileLock);
  end;
end;

(* ArgV *)


{ TLazLoggerFileHandle }

procedure TLazLoggerFileHandle.DoOpenFile;
var
  fm: Byte;
begin
  if FActiveLogText <> nil then exit;

  if (not FLogTextFailed) and (length(FLogName)>0)
     {$ifNdef WinCE}
     and (DirPathExists(ExtractFileDir(FLogName)))
     {$endif}
  then begin
    fm:=Filemode;
    try
      {$ifdef WinCE}
        Assign(FLogText, FLogName);
        {$I-}
        Append(FLogText);
        if IOResult <> 0 then
          Rewrite(FLogText);
        {$I+}
      {$else}
        Filemode:=fmShareDenyNone;
        Assign(FLogText, FLogName);
        if FileExistsUTF8(FLogName) then
          Append(FLogText)
        else
          Rewrite(FLogText);
      {$endif}
      FActiveLogText := @FLogText;
      FLogTextInUse := true;
    except
      FLogTextInUse := false;
      FActiveLogText := nil;
      FLogTextFailed := True;
      // Add extra line ending: a dialog will be shown in windows gui application
      writeln(StdOut, 'Cannot open file: ', FLogName+LineEnding);
    end;
    Filemode:=fm;
  end;

  if (not FLogTextInUse) and (FUseStdOut) then
  begin
    if not(TextRec(Output).Mode=fmClosed) then
      FActiveLogText := @Output;
  end;
end;

procedure TLazLoggerFileHandle.DoCloseFile;
begin
  if FLogTextInUse then begin
    try
      Close(FLogText);
    except
    end;
    FLogTextInUse := false;
  end;
  FActiveLogText := nil;
end;

function TLazLoggerFileHandle.GetWriteTarget: TLazLoggerWriteTarget;
begin
  Result := lwtNone;
  if FActiveLogText = @Output then
    Result := lwtStdOut
  else
  if FLogTextInUse then
    Result := lwtTextFile;
end;

procedure TLazLoggerFileHandle.SetCloseLogFileBetweenWrites(AValue: Boolean);
begin
  if FCloseLogFileBetweenWrites = AValue then Exit;
  FCloseLogFileBetweenWrites := AValue;
  if FCloseLogFileBetweenWrites then
    DoCloseFile;
end;

procedure TLazLoggerFileHandle.SetLogName(AValue: String);
begin
  if FLogName = AValue then Exit;
  DoCloseFile;

  FLogName := CleanAndExpandFilename(AValue);

  FLogTextFailed := False;
end;

constructor TLazLoggerFileHandle.Create;
begin
  FLogTextInUse := False;
  FLogTextFailed := False;
  {$ifdef WinCE}
  FLogName := ExtractFilePath(ParamStr(0)) + Str_LCL_Debug_File;
  FUseStdOut := False;
  FCloseLogFileBetweenWrites := True;
  {$else}
  FLogName := '';
  FUseStdOut := True;
  FCloseLogFileBetweenWrites := False;
  {$endif}
end;

destructor TLazLoggerFileHandle.Destroy;
begin
  inherited Destroy;
  DoCloseFile;
end;

procedure TLazLoggerFileHandle.OpenFile;
begin
  if not CloseLogFileBetweenWrites then
    DoOpenFile;
end;

procedure TLazLoggerFileHandle.CloseFile;
begin
  DoCloseFile;
  FLogTextFailed := False;
end;

procedure TLazLoggerFileHandle.ResetWriteFailedCounter;
begin
  FWriteFailedCount := 0;
end;

procedure TLazLoggerFileHandle.WriteToFile(const s: string);
begin
  try
  DoOpenFile;
  if FActiveLogText = nil then exit;

  Write(FActiveLogText^, s);

  if FCloseLogFileBetweenWrites then
    DoCloseFile;
    FLastWriteFailed := False;
  except
    inc(FWriteFailedCount);
    FLastWriteFailed := True;
  end;
end;

procedure TLazLoggerFileHandle.WriteLnToFile(const s: string);
begin
  try
  DoOpenFile;
  if FActiveLogText = nil then exit;

  WriteLn(FActiveLogText^, s);

  if FCloseLogFileBetweenWrites then
    DoCloseFile;
    FLastWriteFailed := False;
  except
    inc(FWriteFailedCount);
    FLastWriteFailed := True;
  end;
end;

{ TLazLoggerFile }

function TLazLoggerFile.GetFileHandle: TLazLoggerFileHandle;
begin
  if FFileHandle = nil then
    FFileHandle := TLazLoggerFileHandleMainThread.Create;
  Result := FFileHandle;
end;

procedure TLazLoggerFile.SetEnvironmentForLogFileName(AValue: String);
begin
  if FEnvironmentForLogFileName = AValue then Exit;
  Finish;
  FGetLogFileNameDone := False;
  FEnvironmentForLogFileName := AValue;
end;

procedure TLazLoggerFile.SetFileHandle(AValue: TLazLoggerFileHandle);
begin
  if FFileHandle = AValue then Exit;
  Finish;
  FreeAndNil(FFileHandle);
  FFileHandle := AValue;
end;

procedure TLazLoggerFile.SetParamForLogFileName(AValue: String);
begin
  if FParamForLogFileName = AValue then Exit;
  Finish;
  FGetLogFileNameDone := False;
  FParamForLogFileName := AValue;
end;

function TLazLoggerFile.GetCloseLogFileBetweenWrites: Boolean;
begin
  Result := FileHandle.CloseLogFileBetweenWrites;
end;

function TLazLoggerFile.GetLogName: String;
begin
  Result := FileHandle.LogName;
end;

function TLazLoggerFile.GetUseStdOut: Boolean;
begin
  Result := FileHandle.UseStdOut;
end;

procedure TLazLoggerFile.SetCloseLogFileBetweenWrites(AValue: Boolean);
begin
  FileHandle.CloseLogFileBetweenWrites := AValue;
end;

procedure TLazLoggerFile.SetLogName(AValue: String);
begin
  if FileHandle.LogName = AValue then Exit;
  Finish;
  FileHandle.LogName := AValue;
end;

procedure TLazLoggerFile.SetUseStdOut(AValue: Boolean);
begin
  FileHandle.UseStdOut := AValue;
end;

procedure TLazLoggerFile.DoInit;
begin
  inherited DoInit;

  FDebugNestLvl := 0;
  FDebugNestAtBOL := True;
  if (LogName = '') and not FGetLogFileNameDone then
    LogName := GetLogFileName;

  FileHandle.OpenFile;
end;

procedure TLazLoggerFile.DoFinsh;
begin
  inherited DoFinsh;

  FileHandle.CloseFile;
end;

procedure TLazLoggerFile.IncreaseIndent;
var
  i: Integer;
begin
  inc(FDebugNestLvl);
  CreateIndent;
  for i := 0 to BlockHandlerCount - 1 do
    BlockHandler[i].EnterBlock(Self, FDebugNestLvl);
end;

procedure TLazLoggerFile.DecreaseIndent;
var
  i: Integer;
begin
  if not FDebugNestAtBOL then DebugLn;

  if FDebugNestLvl > 0 then begin
    for i := 0 to BlockHandlerCount - 1 do
      BlockHandler[i].ExitBlock(Self, FDebugNestLvl);
    dec(FDebugNestLvl);
  end;
  CreateIndent;
end;

procedure TLazLoggerFile.IncreaseIndent(LogGroup: PLazLoggerLogGroup);
begin
  if (LogGroup <> nil) then begin
    if (not LogGroup^.Enabled) then exit;
    inc(LogGroup^.FOpenedIndents);
    IncreaseIndent;
  end
  else
    IncreaseIndent;
end;

procedure TLazLoggerFile.DecreaseIndent(LogGroup: PLazLoggerLogGroup);
begin
  if (LogGroup <> nil) then begin
    // close what was opened, even if now disabled
    // only close, if opened by this group
    if (LogGroup^.FOpenedIndents <= 0) then exit;
    dec(LogGroup^.FOpenedIndents);
    DecreaseIndent;
  end
  else
    DecreaseIndent;
end;

procedure TLazLoggerFile.IndentChanged;
begin
  CreateIndent;
end;

procedure TLazLoggerFile.CreateIndent;
var
  s: String;
  NewLen: Integer;
begin
  NewLen := FDebugNestLvl * NestLvlIndent;
  if NewLen < 0 then NewLen := 0;
  if (NewLen >= MaxNestPrefixLen) then begin
    s := IntToStr(FDebugNestLvl);
    NewLen := MaxNestPrefixLen - Length(s);
    if NewLen < 1 then
      NewLen := 1;
  end else
    s := '';

  EnterCriticalsection(FIndentCriticalSection);
  if NewLen <> Length(FDebugIndent) then
    FDebugIndent := s + StringOfChar(' ', NewLen);
  LeaveCriticalsection(FIndentCriticalSection);
end;

function TLazLoggerFile.GetBlockHandler(AIndex: Integer): TLazLoggerBlockHandler;
begin
  Result := TLazLoggerBlockHandler(FBlockHandler[AIndex]);
end;

procedure TLazLoggerFile.ClearAllBlockHandler;
begin
  while BlockHandlerCount > 0 do RemoveBlockHandler(BlockHandler[0]);
end;

procedure TLazLoggerFile.DoDbgOut(const s: string);
var
  Handled: Boolean;
  s2: String;
begin
  if not IsInitialized then Init;

  EnterCriticalsection(FIndentCriticalSection);
  s2 := FDebugIndent + s;
  LeaveCriticalsection(FIndentCriticalSection);

  if OnDbgOut <> nil then
  begin
    Handled := False;
    if FDebugNestAtBOL and (s <> '') then
      OnDbgOut(Self, s2, Handled)
    else
      OnDbgOut(Self, s, Handled);
    if Handled then
      Exit;
  end;

  if OnWidgetSetDbgOut <> nil then
  begin
    Handled := False;
    if FDebugNestAtBOL and (s <> '') then
      OnWidgetSetDbgOut(Self, s2, Handled,
                        FileHandle.WriteTarget, FileHandle.ActiveLogText)
    else
      OnWidgetSetDbgOut(Self, s, Handled, FileHandle.WriteTarget, FileHandle.ActiveLogText);
    if Handled then
      Exit;
  end;

  if FDebugNestAtBOL and (s <> '') then
    FileHandle.WriteToFile(s2)
  else
    FileHandle.WriteToFile(s);
  FDebugNestAtBOL := (s = '') or (s[length(s)] in [#10,#13]);
end;

procedure TLazLoggerFile.DoDebugLn(const s: string);
var
  Handled: Boolean;
  s2: String;
begin
  if not IsInitialized then Init;

  EnterCriticalsection(FIndentCriticalSection);
  s2 := FDebugIndent + s;
  LeaveCriticalsection(FIndentCriticalSection);

  if OnDebugLn <> nil then
  begin
    Handled := False;
    if FDebugNestAtBOL and (s <> '') then
      OnDebugLn(Self, s2, Handled)
    else
      OnDebugLn(Self, s, Handled);
    if Handled then
      Exit;
  end;

  if OnWidgetSetDebugLn <> nil then
  begin
    Handled := False;
    if FDebugNestAtBOL and (s <> '') then
      OnWidgetSetDebugLn(Self, s2, Handled,
                         FileHandle.WriteTarget, FileHandle.ActiveLogText)
    else
      OnWidgetSetDebugLn(Self, s, Handled, FileHandle.WriteTarget, FileHandle.ActiveLogText);
    if Handled then
      Exit;
  end;

  if FDebugNestAtBOL and (s <> '') then
    FileHandle.WriteLnToFile(LineBreaksToSystemLineBreaks(s2))
  else
    FileHandle.WriteLnToFile(ConvertLineEndings(s));
  FDebugNestAtBOL := True;
end;

procedure TLazLoggerFile.DoDebuglnStack(const s: string);
begin
  DebugLn(s);
  FileHandle.DoOpenFile;
  if FileHandle.FActiveLogText = nil then exit;

  Dump_Stack(FileHandle.FActiveLogText^, get_frame);

  if CloseLogFileBetweenWrites then
    FileHandle.DoCloseFile;
end;

constructor TLazLoggerFile.Create;
begin
  InitCriticalSection(FIndentCriticalSection);
  inherited;
  FDebugNestLvl := 0;
  FBlockHandler := TList.Create;

  {$ifdef WinCE}
  FParamForLogFileName := '';
  FEnvironmentForLogFileName := '';
  {$else}
  FParamForLogFileName := '--debug-log=';
  FEnvironmentForLogFileName   := '*_debuglog';
  {$endif}
end;

destructor TLazLoggerFile.Destroy;
begin
  ClearAllBlockHandler;
  inherited Destroy;
  FreeAndNil(FFileHandle);
  FreeAndNil(FBlockHandler);
  DoneCriticalsection(FIndentCriticalSection);
end;

procedure TLazLoggerFile.Assign(Src: TLazLogger);
begin
  inherited Assign(Src);
  if (Src <> nil) and (Src is TLazLoggerFile) then begin
    FOnDbgOut  := TLazLoggerFile(Src).FOnDbgOut;
    FOnDebugLn := TLazLoggerFile(Src).FOnDebugLn;;

    FEnvironmentForLogFileName := TLazLoggerFile(Src).FEnvironmentForLogFileName;
    FParamForLogFileName       := TLazLoggerFile(Src).FParamForLogFileName;
    FGetLogFileNameDone        := TLazLoggerFile(Src).FGetLogFileNameDone;

    LogName   := TLazLoggerFile(Src).LogName;
    UseStdOut := TLazLoggerFile(Src).UseStdOut;
    CloseLogFileBetweenWrites := TLazLoggerFile(Src).CloseLogFileBetweenWrites;
  end;
end;

function TLazLoggerFile.CurrentIndentLevel: Integer;
begin
  Result := FDebugNestLvl;
end;

procedure TLazLoggerFile.AddBlockHandler(AHandler: TLazLoggerBlockHandler);
begin
  FBlockHandler.Add(AHandler);
  AHandler.AddReference;
end;

procedure TLazLoggerFile.RemoveBlockHandler(AHandler: TLazLoggerBlockHandler);
begin
  FBlockHandler.Remove(AHandler);
  AHandler.ReleaseReference;
end;

function TLazLoggerFile.BlockHandlerCount: Integer;
begin
  Result := FBlockHandler.Count;
end;

function TLazLoggerFile.GetLogFileName: string;
var
  EnvVarName: string;
  i: Integer;
begin
  Result := '';
  FGetLogFileNameDone := True;
  if FParamForLogFileName <> '' then begin
    // first try to find the log file name in the command line parameters
    i := GetParamByNameCount(FParamForLogFileName) - 1;
    if i >= 0 then
      Result := GetParamByName(FParamForLogFileName, i);
  end;
  if FEnvironmentForLogFileName <> '' then begin;
    // if not found yet, then try to find in the environment variables
    if (length(result)=0) then begin
      // Substitute * with executable filename without extension
      EnvVarName:=StringReplace(FEnvironmentForLogFileName,
        '*',
        ChangeFileExt(ExtractFileName(ParamStrUTF8(0)),''),
        [rfReplaceAll,rfIgnoreCase]);
      Result := GetEnvironmentVariableUTF8(EnvVarName);
    end;
  end;
  if (length(result)>0) then
    Result := ExpandFileNameUTF8(Result);
end;


function DbgStr(const StringWithSpecialChars: string): string;
begin
  Result := LazLoggerBase.DbgStr(StringWithSpecialChars);
end;

function DbgStr(const StringWithSpecialChars: string; StartPos, Len: PtrInt
  ): string;
begin
  Result := LazLoggerBase.DbgStr(StringWithSpecialChars, StartPos, Len);
end;

function DbgStr(const p: PChar; Len: PtrInt): string;
begin
  Result := LazLoggerBase.DbgStr(p, Len);
end;

function DbgWideStr(const StringWithSpecialChars: widestring): string;
begin
  Result := LazLoggerBase.DbgWideStr(StringWithSpecialChars);
end;

initialization
  LazDebugLoggerCreator := @CreateDebugLogger;
  RecreateDebugLogger;
end.