-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
FileTarget.cs
2381 lines (2137 loc) · 101 KB
/
FileTarget.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) 2004-2019 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT && !__ANDROID__ && !__IOS__ && !NETSTANDARD1_3
// Unfortunately, Xamarin Android and Xamarin iOS don't support mutexes (see https://github.com/mono/mono/blob/3a9e18e5405b5772be88bfc45739d6a350560111/mcs/class/corlib/System.Threading/Mutex.cs#L167) so the BaseFileAppender class now throws an exception in the constructor.
#define SupportsMutex
#endif
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
#if !SILVERLIGHT
using System.IO.Compression;
#endif
using System.Text;
using System.Threading;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Internal.FileAppenders;
using NLog.Layouts;
using NLog.Targets.FileArchiveModes;
using NLog.Time;
/// <summary>
/// Writes log messages to one or more files.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/File-target">Documentation on NLog Wiki</seealso>
[Target("File")]
public class FileTarget : TargetWithLayoutHeaderAndFooter, ICreateFileParameters
{
/// <summary>
/// Default clean up period of the initilized files. When a file exceeds the clean up period is removed from the list.
/// </summary>
/// <remarks>Clean up period is defined in days.</remarks>
private const int InitializedFilesCleanupPeriod = 2;
/// <summary>
/// The maximum number of initialised files before clean up procedures are initiated,
/// to keep the number of initialised files to a minimum. Chose 25 to cater for monthly rolling of log-files.
/// </summary>
private const int InitializedFilesCounterMax = 25;
/// <summary>
/// This value disables file archiving based on the size.
/// </summary>
private const int ArchiveAboveSizeDisabled = -1;
/// <summary>
/// Holds the initialised files each given time by the <see cref="FileTarget"/> instance. Against each file, the last write time is stored.
/// </summary>
/// <remarks>Last write time is store in local time (no UTC).</remarks>
private readonly Dictionary<string, DateTime> _initializedFiles = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// List of the associated file appenders with the <see cref="FileTarget"/> instance.
/// </summary>
private FileAppenderCache _fileAppenderCache;
IFileArchiveMode GetFileArchiveHelper(string archiveFilePattern)
{
return _fileArchiveHelper ?? (_fileArchiveHelper = FileArchiveModeFactory.CreateArchiveStyle(archiveFilePattern, ArchiveNumbering, GetArchiveDateFormatString(ArchiveDateFormat), ArchiveFileName != null, MaxArchiveFiles));
}
private IFileArchiveMode _fileArchiveHelper;
private Timer _autoClosingTimer;
/// <summary>
/// The number of initialised files at any one time.
/// </summary>
private int _initializedFilesCounter;
/// <summary>
/// The maximum number of archive files that should be kept.
/// </summary>
private int _maxArchiveFiles;
/// <summary>
/// The filename as target
/// </summary>
private FilePathLayout _fullFileName;
/// <summary>
/// The archive file name as target
/// </summary>
private FilePathLayout _fullArchiveFileName;
private FileArchivePeriod _archiveEvery;
private long _archiveAboveSize;
private bool _enableArchiveFileCompression;
/// <summary>
/// The date of the previous log event.
/// </summary>
private DateTime? _previousLogEventTimestamp;
/// <summary>
/// The file name of the previous log event.
/// </summary>
private string _previousLogFileName;
private bool? _concurrentWrites;
private bool _keepFileOpen;
private bool _cleanupFileName;
private FilePathKind _fileNameKind;
private FilePathKind _archiveFileKind;
/// <summary>
/// Initializes a new instance of the <see cref="FileTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
public FileTarget()
{
ArchiveNumbering = ArchiveNumberingMode.Sequence;
_maxArchiveFiles = 0;
ConcurrentWriteAttemptDelay = 1;
ArchiveEvery = FileArchivePeriod.None;
ArchiveAboveSize = ArchiveAboveSizeDisabled;
ConcurrentWriteAttempts = 10;
ConcurrentWrites = true;
#if SILVERLIGHT || NETSTANDARD1_0
Encoding = Encoding.UTF8;
#else
Encoding = Encoding.Default;
#endif
BufferSize = 32768;
AutoFlush = true;
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
FileAttributes = Win32FileAttributes.Normal;
#endif
LineEnding = LineEndingMode.Default;
EnableFileDelete = true;
OpenFileCacheTimeout = -1;
OpenFileCacheSize = 5;
CreateDirs = true;
ForceManaged = false;
ArchiveDateFormat = string.Empty;
_fileAppenderCache = FileAppenderCache.Empty;
CleanupFileName = true;
WriteFooterOnArchivingOnly = false;
OptimizeBufferReuse = GetType() == typeof(FileTarget); // Class not sealed, reduce breaking changes
}
#if NET4_5
static FileTarget()
{
FileCompressor = new ZipArchiveFileCompressor();
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="FileTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
/// <param name="name">Name of the target.</param>
public FileTarget(string name) : this()
{
Name = name;
}
/// <summary>
/// Gets or sets the name of the file to write to.
/// </summary>
/// <remarks>
/// This FileName string is a layout which may include instances of layout renderers.
/// This lets you use a single target to write to multiple files.
/// </remarks>
/// <example>
/// The following value makes NLog write logging events to files based on the log level in the directory where
/// the application runs.
/// <code>${basedir}/${level}.log</code>
/// All <c>Debug</c> messages will go to <c>Debug.log</c>, all <c>Info</c> messages will go to <c>Info.log</c> and so on.
/// You can combine as many of the layout renderers as you want to produce an arbitrary log file name.
/// </example>
/// <docgen category='Output Options' order='1' />
[RequiredParameter]
public Layout FileName
{
get
{
return _fullFileName?.GetLayout();
}
set
{
_fullFileName = CreateFileNameLayout(value);
ResetFileAppenders("FileName Changed");
}
}
private FilePathLayout CreateFileNameLayout(Layout value)
{
if (value == null)
return null;
return new FilePathLayout(value, CleanupFileName, FileNameKind);
}
/// <summary>
/// Cleanup invalid values in a filename, e.g. slashes in a filename. If set to <c>true</c>, this can impact the performance of massive writes.
/// If set to <c>false</c>, nothing gets written when the filename is wrong.
/// </summary>
/// <docgen category='Output Options' order='10' />
[DefaultValue(true)]
public bool CleanupFileName
{
get => _cleanupFileName;
set
{
if (_cleanupFileName != value)
{
_cleanupFileName = value;
_fullFileName = CreateFileNameLayout(FileName);
_fullArchiveFileName = CreateFileNameLayout(ArchiveFileName);
ResetFileAppenders("CleanupFileName Changed");
}
}
}
/// <summary>
/// Is the <see cref="FileName"/> an absolute or relative path?
/// </summary>
/// <docgen category='Output Options' order='10' />
[DefaultValue(FilePathKind.Unknown)]
public FilePathKind FileNameKind
{
get => _fileNameKind;
set
{
if (_fileNameKind != value)
{
_fileNameKind = value;
_fullFileName = CreateFileNameLayout(FileName);
ResetFileAppenders("FileNameKind Changed");
}
}
}
/// <summary>
/// Gets or sets a value indicating whether to create directories if they do not exist.
/// </summary>
/// <remarks>
/// Setting this to false may improve performance a bit, but you'll receive an error
/// when attempting to write to a directory that's not present.
/// </remarks>
/// <docgen category='Output Options' order='10' />
[DefaultValue(true)]
[Advanced]
public bool CreateDirs { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to delete old log file on startup.
/// </summary>
/// <remarks>
/// This option works only when the "FileName" parameter denotes a single file.
/// </remarks>
/// <docgen category='Output Options' order='10' />
[DefaultValue(false)]
public bool DeleteOldFileOnStartup { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to replace file contents on each write instead of appending log message at the end.
/// </summary>
/// <docgen category='Output Options' order='10' />
[DefaultValue(false)]
[Advanced]
public bool ReplaceFileContentsOnEachWrite { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to keep log file open instead of opening and closing it on each logging event.
/// </summary>
/// <remarks>
/// Setting this property to <c>True</c> helps improve performance.
/// </remarks>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(false)]
public bool KeepFileOpen
{
get => _keepFileOpen;
set
{
if (_keepFileOpen != value)
{
_keepFileOpen = value;
ResetFileAppenders("KeepFileOpen Changed");
}
}
}
/// <summary>
/// Gets or sets the maximum number of log filenames that should be stored as existing.
/// </summary>
/// <remarks>
/// The bigger this number is the longer it will take to write each log record. The smaller the number is
/// the higher the chance that the clean function will be run when no new files have been opened.
/// </remarks>
[Obsolete("This option will be removed in NLog 5. Marked obsolete on NLog 4.5")]
[DefaultValue(0)]
public int maxLogFilenames { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to enable log file(s) to be deleted.
/// </summary>
/// <docgen category='Output Options' order='10' />
[DefaultValue(true)]
public bool EnableFileDelete { get; set; }
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
/// <summary>
/// Gets or sets the file attributes (Windows only).
/// </summary>
/// <docgen category='Output Options' order='10' />
[Advanced]
public Win32FileAttributes FileAttributes { get; set; }
#endif
bool ICreateFileParameters.IsArchivingEnabled => IsArchivingEnabled;
/// <summary>
/// Gets or sets the line ending mode.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[Advanced]
public LineEndingMode LineEnding { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to automatically flush the file buffers after each log message.
/// </summary>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(true)]
public bool AutoFlush { get; set; }
/// <summary>
/// Gets or sets the number of files to be kept open. Setting this to a higher value may improve performance
/// in a situation where a single File target is writing to many files
/// (such as splitting by level or by logger).
/// </summary>
/// <remarks>
/// The files are managed on a LRU (least recently used) basis, which flushes
/// the files that have not been used for the longest period of time should the
/// cache become full. As a rule of thumb, you shouldn't set this parameter to
/// a very high value. A number like 10-15 shouldn't be exceeded, because you'd
/// be keeping a large number of files open which consumes system resources.
/// </remarks>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(5)]
[Advanced]
public int OpenFileCacheSize { get; set; }
/// <summary>
/// Gets or sets the maximum number of seconds that files are kept open. If this number is negative the files are
/// not automatically closed after a period of inactivity.
/// </summary>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(-1)]
[Advanced]
public int OpenFileCacheTimeout { get; set; }
/// <summary>
/// Gets or sets the maximum number of seconds before open files are flushed. If this number is negative or zero
/// the files are not flushed by timer.
/// </summary>
/// <docgen category='Performance Tuning Options' order='10' />
public int OpenFileFlushTimeout { get; set; }
/// <summary>
/// Gets or sets the log file buffer size in bytes.
/// </summary>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(32768)]
public int BufferSize { get; set; }
/// <summary>
/// Gets or sets the file encoding.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public Encoding Encoding { get; set; }
/// <summary>
/// Gets or sets whether or not this target should just discard all data that its asked to write.
/// Mostly used for when testing NLog Stack except final write
/// </summary>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(false)]
[Advanced]
public bool DiscardAll { get; set; }
/// <summary>
/// Gets or sets a value indicating whether concurrent writes to the log file by multiple processes on the same host.
/// </summary>
/// <remarks>
/// This makes multi-process logging possible. NLog uses a special technique
/// that lets it keep the files open for writing.
/// </remarks>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(true)]
public bool ConcurrentWrites
{
get
{
#if SupportsMutex
return _concurrentWrites ?? PlatformDetector.SupportsSharableMutex;
#else
return _concurrentWrites ?? false; // Better user experience for mobile platforms
#endif
}
set
{
if (_concurrentWrites != value)
{
_concurrentWrites = value;
ResetFileAppenders("ConcurrentWrites Changed");
}
}
}
/// <summary>
/// Gets or sets a value indicating whether concurrent writes to the log file by multiple processes on different network hosts.
/// </summary>
/// <remarks>
/// This effectively prevents files from being kept open.
/// </remarks>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(false)]
public bool NetworkWrites { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to write BOM (byte order mark) in created files
/// </summary>
/// <docgen category='Output Options' order='10' />
[DefaultValue(false)]
public bool WriteBom { get; set; }
/// <summary>
/// Gets or sets the number of times the write is appended on the file before NLog
/// discards the log message.
/// </summary>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(10)]
[Advanced]
public int ConcurrentWriteAttempts { get; set; }
/// <summary>
/// Gets or sets the delay in milliseconds to wait before attempting to write to the file again.
/// </summary>
/// <remarks>
/// The actual delay is a random value between 0 and the value specified
/// in this parameter. On each failed attempt the delay base is doubled
/// up to <see cref="ConcurrentWriteAttempts" /> times.
/// </remarks>
/// <example>
/// Assuming that ConcurrentWriteAttemptDelay is 10 the time to wait will be:<p/>
/// a random value between 0 and 10 milliseconds - 1st attempt<br/>
/// a random value between 0 and 20 milliseconds - 2nd attempt<br/>
/// a random value between 0 and 40 milliseconds - 3rd attempt<br/>
/// a random value between 0 and 80 milliseconds - 4th attempt<br/>
/// ...<p/>
/// and so on.
/// </example>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(1)]
[Advanced]
public int ConcurrentWriteAttemptDelay { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to archive old log file on startup.
/// </summary>
/// <remarks>
/// This option works only when the "FileName" parameter denotes a single file.
/// After archiving the old file, the current log file will be empty.
/// </remarks>
/// <docgen category='Output Options' order='10' />
[DefaultValue(false)]
public bool ArchiveOldFileOnStartup { get; set; }
/// <summary>
/// Gets or sets a value specifying the date format to use when archiving files.
/// </summary>
/// <remarks>
/// This option works only when the "ArchiveNumbering" parameter is set either to Date or DateAndSequence.
/// </remarks>
/// <docgen category='Output Options' order='10' />
[DefaultValue("")]
public string ArchiveDateFormat
{
get => _archiveDateFormat;
set
{
if (_archiveDateFormat != value)
{
_archiveDateFormat = value;
ResetFileAppenders("ArchiveDateFormat Changed"); // Reset archive file-monitoring
}
}
}
private string _archiveDateFormat;
/// <summary>
/// Gets or sets the size in bytes above which log files will be automatically archived.
///
/// Warning: combining this with <see cref="ArchiveNumberingMode.Date"/> isn't supported. We cannot create multiple archive files, if they should have the same name.
/// Choose: <see cref="ArchiveNumberingMode.DateAndSequence"/>
/// </summary>
/// <remarks>
/// Caution: Enabling this option can considerably slow down your file
/// logging in multi-process scenarios. If only one process is going to
/// be writing to the file, consider setting <c>ConcurrentWrites</c>
/// to <c>false</c> for maximum performance.
/// </remarks>
/// <docgen category='Archival Options' order='10' />
public long ArchiveAboveSize
{
get => _archiveAboveSize;
set
{
if ((_archiveAboveSize == ArchiveAboveSizeDisabled) != (value == ArchiveAboveSizeDisabled))
{
_archiveAboveSize = value;
ResetFileAppenders("ArchiveAboveSize Changed"); // Reset archive file-monitoring
}
else
{
_archiveAboveSize = value;
}
}
}
/// <summary>
/// Gets or sets a value indicating whether to automatically archive log files every time the specified time passes.
/// </summary>
/// <remarks>
/// Files are moved to the archive as part of the write operation if the current period of time changes. For example
/// if the current <c>hour</c> changes from 10 to 11, the first write that will occur
/// on or after 11:00 will trigger the archiving.
/// <p>
/// Caution: Enabling this option can considerably slow down your file
/// logging in multi-process scenarios. If only one process is going to
/// be writing to the file, consider setting <c>ConcurrentWrites</c>
/// to <c>false</c> for maximum performance.
/// </p>
/// </remarks>
/// <docgen category='Archival Options' order='10' />
public FileArchivePeriod ArchiveEvery
{
get => _archiveEvery;
set
{
if (_archiveEvery != value)
{
_archiveEvery = value;
ResetFileAppenders("ArchiveEvery Changed"); // Reset archive file-monitoring
}
}
}
/// <summary>
/// Is the <see cref="ArchiveFileName"/> an absolute or relative path?
/// </summary>
/// <docgen category='Archival Options' order='10' />
public FilePathKind ArchiveFileKind
{
get => _archiveFileKind;
set
{
if (_archiveFileKind != value)
{
_archiveFileKind = value;
_fullArchiveFileName = CreateFileNameLayout(ArchiveFileName);
ResetFileAppenders("ArchiveFileKind Changed"); // Reset archive file-monitoring
}
}
}
/// <summary>
/// Gets or sets the name of the file to be used for an archive.
/// </summary>
/// <remarks>
/// It may contain a special placeholder {#####}
/// that will be replaced with a sequence of numbers depending on
/// the archiving strategy. The number of hash characters used determines
/// the number of numerical digits to be used for numbering files.
/// </remarks>
/// <docgen category='Archival Options' order='10' />
public Layout ArchiveFileName
{
get
{
if (_fullArchiveFileName == null) return null;
return _fullArchiveFileName.GetLayout();
}
set
{
_fullArchiveFileName = CreateFileNameLayout(value);
ResetFileAppenders("ArchiveFileName Changed"); // Reset archive file-monitoring
}
}
/// <summary>
/// Gets or sets the maximum number of archive files that should be kept.
/// </summary>
/// <docgen category='Archival Options' order='10' />
[DefaultValue(0)]
public int MaxArchiveFiles
{
get => _maxArchiveFiles;
set
{
if (_maxArchiveFiles != value)
{
_maxArchiveFiles = value;
ResetFileAppenders("MaxArchiveFiles Changed"); // Enforce archive cleanup
}
}
}
/// <summary>
/// Gets or sets the way file archives are numbered.
/// </summary>
/// <docgen category='Archival Options' order='10' />
public ArchiveNumberingMode ArchiveNumbering
{
get => _archiveNumbering;
set
{
if (_archiveNumbering != value)
{
_archiveNumbering = value;
ResetFileAppenders("ArchiveNumbering Changed"); // Reset archive file-monitoring
}
}
}
private ArchiveNumberingMode _archiveNumbering;
/// <summary>
/// Used to compress log files during archiving.
/// This may be used to provide your own implementation of a zip file compressor,
/// on platforms other than .Net4.5.
/// Defaults to ZipArchiveFileCompressor on .Net4.5 and to null otherwise.
/// </summary>
/// <docgen category='Output Options' order='10' />
public static IFileCompressor FileCompressor { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to compress archive files into the zip archive format.
/// </summary>
/// <docgen category='Archival Options' order='10' />
[DefaultValue(false)]
public bool EnableArchiveFileCompression
{
get => _enableArchiveFileCompression && FileCompressor != null;
set
{
if (_enableArchiveFileCompression != value)
{
_enableArchiveFileCompression = value;
ResetFileAppenders("EnableArchiveFileCompression Changed"); // Reset archive file-monitoring
}
}
}
/// <summary>
/// Gets or set a value indicating whether a managed file stream is forced, instead of using the native implementation.
/// </summary>
/// <docgen category='Output Options' order='10' />
[DefaultValue(false)]
public bool ForceManaged { get; set; }
#if SupportsMutex
/// <summary>
/// Gets or sets a value indicating whether file creation calls should be synchronized by a system global mutex.
/// </summary>
/// <docgen category='Output Options' order='10' />
[DefaultValue(false)]
public bool ForceMutexConcurrentWrites { get; set; }
#endif
/// <summary>
/// Gets or sets a value indicating whether the footer should be written only when the file is archived.
/// </summary>
/// <docgen category='Archival Options' order='10' />
[DefaultValue(false)]
public bool WriteFooterOnArchivingOnly { get; set; }
/// <summary>
/// Gets the characters that are appended after each line.
/// </summary>
protected internal string NewLineChars => LineEnding.NewLineCharacters;
/// <summary>
/// Refresh the ArchiveFilePatternToWatch option of the <see cref="FileAppenderCache" />.
/// The log file must be watched for archiving when multiple processes are writing to the same
/// open file.
/// </summary>
private void RefreshArchiveFilePatternToWatch(string fileName, LogEventInfo logEvent)
{
if (_fileAppenderCache != null)
{
_fileAppenderCache.CheckCloseAppenders -= AutoCloseAppendersAfterArchive;
bool mustWatchArchiving = IsArchivingEnabled && KeepFileOpen && ConcurrentWrites;
bool mustWatchActiveFile = KeepFileOpen && EnableFileDelete && !NetworkWrites && !ReplaceFileContentsOnEachWrite && !EnableFileDeleteSimpleMonitor;
if (mustWatchArchiving || mustWatchActiveFile)
{
_fileAppenderCache.CheckCloseAppenders += AutoCloseAppendersAfterArchive; // Activates FileSystemWatcher
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD1_3
if (mustWatchArchiving)
{
string fileNamePattern = GetArchiveFileNamePattern(fileName, logEvent);
var fileArchiveStyle = !string.IsNullOrEmpty(fileNamePattern) ? GetFileArchiveHelper(fileNamePattern) : null;
string fileNameMask = fileArchiveStyle != null ? _fileArchiveHelper.GenerateFileNameMask(fileNamePattern) : string.Empty;
string directoryMask = !string.IsNullOrEmpty(fileNameMask) ? Path.Combine(Path.GetDirectoryName(fileNamePattern), fileNameMask) : string.Empty;
_fileAppenderCache.ArchiveFilePatternToWatch = directoryMask;
}
else
{
_fileAppenderCache.ArchiveFilePatternToWatch = null;
}
#endif
}
}
/// <summary>
/// Removes records of initialized files that have not been
/// accessed in the last two days.
/// </summary>
/// <remarks>
/// Files are marked 'initialized' for the purpose of writing footers when the logging finishes.
/// </remarks>
public void CleanupInitializedFiles()
{
CleanupInitializedFiles(TimeSource.Current.Time.AddDays(-InitializedFilesCleanupPeriod));
}
/// <summary>
/// Removes records of initialized files that have not been
/// accessed after the specified date.
/// </summary>
/// <param name="cleanupThreshold">The cleanup threshold.</param>
/// <remarks>
/// Files are marked 'initialized' for the purpose of writing footers when the logging finishes.
/// </remarks>
public void CleanupInitializedFiles(DateTime cleanupThreshold)
{
if (InternalLogger.IsTraceEnabled)
{
InternalLogger.Trace("FileTarget(Name={0}): Cleanup Initialized Files with cleanupThreshold {1}", Name, cleanupThreshold);
}
List<string> filesToFinalize = null;
// Select the files require to be finalized.
foreach (var file in _initializedFiles)
{
if (file.Value < cleanupThreshold)
{
if (filesToFinalize == null)
{
filesToFinalize = new List<string>();
}
filesToFinalize.Add(file.Key);
}
}
// Finalize the files.
if (filesToFinalize != null)
{
foreach (string fileName in filesToFinalize)
{
FinalizeFile(fileName);
}
}
InternalLogger.Trace("FileTarget(Name={0}): CleanupInitializedFiles Done", Name);
}
/// <summary>
/// Flushes all pending file operations.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <remarks>
/// The timeout parameter is ignored, because file APIs don't provide
/// the needed functionality.
/// </remarks>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
try
{
InternalLogger.Trace("FileTarget(Name={0}): FlushAsync", Name);
_fileAppenderCache.FlushAppenders();
asyncContinuation(null);
InternalLogger.Trace("FileTarget(Name={0}): FlushAsync Done", Name);
}
catch (Exception exception)
{
InternalLogger.Warn(exception, "FileTarget(Name={0}): Exception in FlushAsync", Name);
if (exception.MustBeRethrown())
{
throw;
}
asyncContinuation(exception);
}
}
/// <summary>
/// Returns the suitable appender factory ( <see cref="IFileAppenderFactory"/>) to be used to generate the file
/// appenders associated with the <see cref="FileTarget"/> instance.
///
/// The type of the file appender factory returned depends on the values of various <see cref="FileTarget"/> properties.
/// </summary>
/// <returns><see cref="IFileAppenderFactory"/> suitable for this instance.</returns>
private IFileAppenderFactory GetFileAppenderFactory()
{
if (DiscardAll)
{
return NullAppender.TheFactory;
}
else if (!KeepFileOpen)
{
return RetryingMultiProcessFileAppender.TheFactory;
}
else if (NetworkWrites)
{
return RetryingMultiProcessFileAppender.TheFactory;
}
else if (ConcurrentWrites)
{
#if SupportsMutex
if (!ForceMutexConcurrentWrites)
{
#if MONO
if (PlatformDetector.IsUnix)
{
return UnixMultiProcessFileAppender.TheFactory;
}
#elif !NETSTANDARD
if (PlatformDetector.IsWin32 && !PlatformDetector.IsMono)
{
return WindowsMultiProcessFileAppender.TheFactory;
}
#endif
}
if (PlatformDetector.SupportsSharableMutex)
{
return MutexMultiProcessFileAppender.TheFactory;
}
else
#endif // SupportsMutex
{
return RetryingMultiProcessFileAppender.TheFactory;
}
}
else if (IsArchivingEnabled)
return CountingSingleProcessFileAppender.TheFactory;
else
return SingleProcessFileAppender.TheFactory;
}
private bool IsArchivingEnabled => ArchiveAboveSize != ArchiveAboveSizeDisabled || ArchiveEvery != FileArchivePeriod.None;
private bool IsSimpleKeepFileOpen => KeepFileOpen && !NetworkWrites && !ReplaceFileContentsOnEachWrite && !ConcurrentWrites;
private bool EnableFileDeleteSimpleMonitor => EnableFileDelete && !PlatformDetector.IsWin32 && IsSimpleKeepFileOpen;
bool ICreateFileParameters.EnableFileDeleteSimpleMonitor => EnableFileDeleteSimpleMonitor;
/// <summary>
/// Initializes file logging by creating data structures that
/// enable efficient multi-file logging.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
var appenderFactory = GetFileAppenderFactory();
if (InternalLogger.IsTraceEnabled)
{
InternalLogger.Trace("FileTarget(Name={0}): Using appenderFactory: {1}", Name, appenderFactory.GetType());
}
_fileAppenderCache = new FileAppenderCache(OpenFileCacheSize, appenderFactory, this);
if ((OpenFileCacheSize > 0 || EnableFileDelete) && (OpenFileCacheTimeout > 0 || OpenFileFlushTimeout > 0))
{
int openFileAutoTimeoutSecs = (OpenFileCacheTimeout > 0 && OpenFileFlushTimeout > 0) ? Math.Min(OpenFileCacheTimeout, OpenFileFlushTimeout) : Math.Max(OpenFileCacheTimeout, OpenFileFlushTimeout);
InternalLogger.Trace("FileTarget(Name={0}): Start autoClosingTimer", Name);
_autoClosingTimer = new Timer(
(state) => AutoClosingTimerCallback(this, EventArgs.Empty),
null,
openFileAutoTimeoutSecs * 1000,
openFileAutoTimeoutSecs * 1000);
}
}
/// <summary>
/// Closes the file(s) opened for writing.
/// </summary>
protected override void CloseTarget()
{
base.CloseTarget();
foreach (string fileName in new List<string>(_initializedFiles.Keys))
{
FinalizeFile(fileName);
}
_fileArchiveHelper = null;
var currentTimer = _autoClosingTimer;
if (currentTimer != null)
{
InternalLogger.Trace("FileTarget(Name={0}): Stop autoClosingTimer", Name);
_autoClosingTimer = null;
currentTimer.WaitForDispose(TimeSpan.Zero);
}
_fileAppenderCache.CloseAppenders("Dispose");
_fileAppenderCache.Dispose();
}
private void ResetFileAppenders(string reason)
{
_fileArchiveHelper = null;
if (IsInitialized)
{
_fileAppenderCache.CloseAppenders(reason);
_initializedFiles.Clear();
}
}
/// <summary>
/// Can be used if <see cref="Target.OptimizeBufferReuse"/> has been enabled.
/// </summary>
private readonly ReusableStreamCreator _reusableFileWriteStream = new ReusableStreamCreator(4096);
/// <summary>
/// Can be used if <see cref="Target.OptimizeBufferReuse"/> has been enabled.
/// </summary>
private readonly ReusableStreamCreator _reusableAsyncFileWriteStream = new ReusableStreamCreator(4096);
/// <summary>
/// Can be used if <see cref="Target.OptimizeBufferReuse"/> has been enabled.
/// </summary>
private readonly ReusableBufferCreator _reusableEncodingBuffer = new ReusableBufferCreator(1024);
/// <summary>
/// Writes the specified logging event to a file specified in the FileName
/// parameter.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(LogEventInfo logEvent)
{
var logFileName = GetFullFileName(logEvent);
if (string.IsNullOrEmpty(logFileName))
{
throw new ArgumentException("The path is not of a legal form.");
}