-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
LogFactory.cs
1204 lines (1080 loc) · 44.4 KB
/
LogFactory.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.
//
namespace NLog
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Threading;
using JetBrains.Annotations;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Targets;
using NLog.Internal.Fakeables;
/// <summary>
/// Creates and manages instances of <see cref="T:NLog.Logger" /> objects.
/// </summary>
public class LogFactory : IDisposable
{
private static readonly TimeSpan DefaultFlushTimeout = TimeSpan.FromSeconds(15);
private static IAppDomain currentAppDomain;
/// <remarks>
/// Internal for unit tests
/// </remarks>
internal readonly object _syncRoot = new object();
internal LoggingConfiguration _config;
private LogLevel _globalThreshold = LogLevel.MinLevel;
private bool _configLoaded;
// TODO: logsEnabled property might be possible to be encapsulated into LogFactory.LogsEnabler class.
private int _logsEnabled;
private readonly LoggerCache _loggerCache = new LoggerCache();
/// <summary>
/// Overwrite possible file paths (including filename) for possible NLog config files.
/// When this property is <c>null</c>, the default file paths (<see cref="GetCandidateConfigFilePaths"/> are used.
/// </summary>
private List<string> _candidateConfigFilePaths;
private readonly ILoggingConfigurationLoader _configLoader;
/// <summary>
/// Occurs when logging <see cref="Configuration" /> changes.
/// </summary>
public event EventHandler<LoggingConfigurationChangedEventArgs> ConfigurationChanged;
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD1_3
/// <summary>
/// Occurs when logging <see cref="Configuration" /> gets reloaded.
/// </summary>
public event EventHandler<LoggingConfigurationReloadedEventArgs> ConfigurationReloaded;
#endif
private static event EventHandler<EventArgs> LoggerShutdown;
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD1_3
/// <summary>
/// Initializes static members of the LogManager class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Significant logic in .cctor()")]
static LogFactory()
{
RegisterEvents(CurrentAppDomain);
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="LogFactory" /> class.
/// </summary>
public LogFactory()
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD1_3
: this(new LoggingConfigurationWatchableFileLoader())
#else
: this(new LoggingConfigurationFileLoader())
#endif
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogFactory" /> class.
/// </summary>
/// <param name="config">The config.</param>
public LogFactory(LoggingConfiguration config)
: this()
{
Configuration = config;
}
/// <summary>
/// Initializes a new instance of the <see cref="LogFactory" /> class.
/// </summary>
/// <param name="configLoader">The config loader</param>
internal LogFactory(ILoggingConfigurationLoader configLoader)
{
_configLoader = configLoader;
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD1_3
LoggerShutdown += OnStopLogging;
#endif
}
/// <summary>
/// Gets the current <see cref="IAppDomain"/>.
/// </summary>
public static IAppDomain CurrentAppDomain
{
get
{
return currentAppDomain ??
#if NETSTANDARD1_0
(currentAppDomain = new FakeAppDomain());
#else
(currentAppDomain = new AppDomainWrapper(AppDomain.CurrentDomain));
#endif
}
set
{
UnregisterEvents(currentAppDomain);
//make sure we aren't double registering.
UnregisterEvents(value);
RegisterEvents(value);
currentAppDomain = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether exceptions should be thrown. See also <see cref="ThrowConfigExceptions"/>.
/// </summary>
/// <value>A value of <c>true</c> if exception should be thrown; otherwise, <c>false</c>.</value>
/// <remarks>By default exceptions are not thrown under any circumstances.</remarks>
public bool ThrowExceptions { get; set; }
/// <summary>
/// Gets or sets a value indicating whether <see cref="NLogConfigurationException"/> should be thrown.
///
/// If <c>null</c> then <see cref="ThrowExceptions"/> is used.
/// </summary>
/// <value>A value of <c>true</c> if exception should be thrown; otherwise, <c>false</c>.</value>
/// <remarks>
/// This option is for backwards-compatiblity.
/// By default exceptions are not thrown under any circumstances.
/// </remarks>
public bool? ThrowConfigExceptions { get; set; }
/// <summary>
/// Gets or sets a value indicating whether Variables should be kept on configuration reload.
/// Default value - false.
/// </summary>
public bool KeepVariablesOnReload { get; set; }
/// <summary>
/// Gets or sets the current logging configuration. After setting this property all
/// existing loggers will be re-configured, so there is no need to call <see cref="ReconfigExistingLoggers" />
/// manually.
/// </summary>
public LoggingConfiguration Configuration
{
get
{
if (_configLoaded)
return _config;
lock (_syncRoot)
{
if (_configLoaded || _isDisposing)
return _config;
var config = _configLoader.Load(this);
if (config != null)
{
try
{
_config = config;
_configLoader.Activated(this, _config);
_config.Dump();
ReconfigExistingLoggers();
LogConfigurationInitialized();
}
finally
{
_configLoaded = true;
}
}
return _config;
}
}
set
{
lock (_syncRoot)
{
LoggingConfiguration oldConfig = _config;
if (oldConfig != null)
{
InternalLogger.Info("Closing old configuration.");
Flush();
oldConfig.Close();
}
_config = value;
if (_config == null)
{
_configLoaded = false;
_configLoader.Activated(this, _config);
}
else
{
try
{
_configLoader.Activated(this, _config);
_config.Dump();
ReconfigExistingLoggers();
}
finally
{
_configLoaded = true;
}
}
OnConfigurationChanged(new LoggingConfigurationChangedEventArgs(value, oldConfig));
}
}
}
/// <summary>
/// Gets or sets the global log level threshold. Log events below this threshold are not logged.
/// </summary>
public LogLevel GlobalThreshold
{
get => _globalThreshold;
set
{
lock (_syncRoot)
{
_globalThreshold = value;
ReconfigExistingLoggers();
}
}
}
/// <summary>
/// Gets the default culture info to use as <see cref="LogEventInfo.FormatProvider"/>.
/// </summary>
/// <value>
/// Specific culture info or null to use <see cref="CultureInfo.CurrentCulture"/>
/// </value>
[CanBeNull]
public CultureInfo DefaultCultureInfo
{
get
{
var configuration = Configuration;
return configuration?.DefaultCultureInfo;
}
}
internal static void LogConfigurationInitialized()
{
InternalLogger.Info("Configuration initialized.");
try
{
InternalLogger.LogAssemblyVersion(typeof(ILogger).GetAssembly());
}
catch (SecurityException ex)
{
InternalLogger.Debug(ex, "Not running in full trust");
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting
/// unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Creates a logger that discards all log messages.
/// </summary>
/// <returns>Null logger instance.</returns>
public Logger CreateNullLogger()
{
return new NullLogger(this);
}
/// <summary>
/// Gets the logger with the name of the current class.
/// </summary>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public Logger GetCurrentClassLogger()
{
#if NETSTANDARD1_0
var className = StackTraceUsageUtils.GetClassFullName();
#elif SILVERLIGHT
var className = StackTraceUsageUtils.GetClassFullName(new StackFrame(1));
#else
var className = StackTraceUsageUtils.GetClassFullName(new StackFrame(1, false));
#endif
return GetLogger(className);
}
/// <summary>
/// Gets the logger with the name of the current class.
/// </summary>
/// <returns>The logger with type <typeparamref name="T"/>.</returns>
/// <typeparam name="T">Type of the logger</typeparam>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public T GetCurrentClassLogger<T>() where T : Logger
{
#if NETSTANDARD1_0
var className = StackTraceUsageUtils.GetClassFullName();
#elif SILVERLIGHT
var className = StackTraceUsageUtils.GetClassFullName(new StackFrame(1));
#else
var className = StackTraceUsageUtils.GetClassFullName(new StackFrame(1, false));
#endif
return (T)GetLogger(className, typeof(T));
}
/// <summary>
/// Gets a custom logger with the name of the current class. Use <paramref name="loggerType"/> to pass the type of the needed Logger.
/// </summary>
/// <param name="loggerType">The type of the logger to create. The type must inherit from <see cref="Logger"/></param>
/// <returns>The logger of type <paramref name="loggerType"/>.</returns>
/// <remarks>This is a slow-running method. Make sure you are not calling this method in a
/// loop.</remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public Logger GetCurrentClassLogger(Type loggerType)
{
#if NETSTANDARD1_0
var className = StackTraceUsageUtils.GetClassFullName();
#elif SILVERLIGHT
var className = StackTraceUsageUtils.GetClassFullName(new StackFrame(1));
#else
var className = StackTraceUsageUtils.GetClassFullName(new StackFrame(1, false));
#endif
return GetLogger(className, loggerType);
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument
/// are not guaranteed to return the same logger reference.</returns>
public Logger GetLogger(string name)
{
return GetLogger(new LoggerCacheKey(name, typeof(Logger)));
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <typeparam name="T">Type of the logger</typeparam>
/// <returns>The logger reference with type <typeparamref name="T"/>. Multiple calls to <c>GetLogger</c> with the same argument
/// are not guaranteed to return the same logger reference.</returns>
public T GetLogger<T>(string name) where T : Logger
{
return (T)GetLogger(new LoggerCacheKey(name, typeof(T)));
}
/// <summary>
/// Gets the specified named logger. Use <paramref name="loggerType"/> to pass the type of the needed Logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <param name="loggerType">The type of the logger to create. The type must inherit from <see cref="Logger" />.</param>
/// <returns>The logger of type <paramref name="loggerType"/>. Multiple calls to <c>GetLogger</c> with the
/// same argument aren't guaranteed to return the same logger reference.</returns>
public Logger GetLogger(string name, Type loggerType)
{
return GetLogger(new LoggerCacheKey(name, loggerType));
}
/// <summary>
/// Loops through all loggers previously returned by GetLogger and recalculates their
/// target and filter list. Useful after modifying the configuration programmatically
/// to ensure that all loggers have been properly configured.
/// </summary>
public void ReconfigExistingLoggers()
{
List<Logger> loggers;
lock (_syncRoot)
{
_config?.InitializeAll();
loggers = _loggerCache.GetLoggers();
}
foreach (var logger in loggers)
{
logger.SetConfiguration(GetConfigurationForLogger(logger.Name, _config));
}
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets) with the default timeout of 15 seconds.
/// </summary>
public void Flush()
{
Flush(DefaultFlushTimeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time
/// will be discarded.</param>
public void Flush(TimeSpan timeout)
{
try
{
AsyncHelpers.RunSynchronously(cb => Flush(cb, timeout));
}
catch (Exception ex)
{
InternalLogger.Error(ex, "Error with flush.");
if (ex.MustBeRethrown())
{
throw;
}
}
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages
/// after that time will be discarded.</param>
public void Flush(int timeoutMilliseconds)
{
Flush(TimeSpan.FromMilliseconds(timeoutMilliseconds));
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public void Flush(AsyncContinuation asyncContinuation)
{
Flush(asyncContinuation, TimeSpan.MaxValue);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages
/// after that time will be discarded.</param>
public void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds)
{
Flush(asyncContinuation, TimeSpan.FromMilliseconds(timeoutMilliseconds));
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout)
{
try
{
InternalLogger.Trace("LogFactory.Flush({0})", timeout);
LoggingConfiguration loggingConfiguration = null;
lock (_syncRoot)
{
loggingConfiguration = _config; // Flush should not attempt to auto-load Configuration
}
if (loggingConfiguration != null)
{
loggingConfiguration.FlushAllTargets(AsyncHelpers.WithTimeout(asyncContinuation, timeout));
}
else
{
asyncContinuation(null);
}
}
catch (Exception ex)
{
if (ThrowExceptions)
{
throw;
}
InternalLogger.Error(ex, "Error with flush.");
}
}
/// <summary>
/// Decreases the log enable counter and if it reaches -1 the logs are disabled.
/// </summary>
/// <remarks>
/// Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater than
/// or equal to <see cref="SuspendLogging"/> calls.
///
/// This method was marked as obsolete on NLog 4.0 and it may be removed in a future release.
/// </remarks>
/// <returns>An object that implements IDisposable whose Dispose() method re-enables logging.
/// To be used with C# <c>using ()</c> statement.</returns>
[Obsolete("Use SuspendLogging() instead. Marked obsolete on NLog 4.0")]
public IDisposable DisableLogging()
{
return SuspendLogging();
}
/// <summary>
/// Increases the log enable counter and if it reaches 0 the logs are disabled.
/// </summary>
/// <remarks>
/// Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater than
/// or equal to <see cref="SuspendLogging"/> calls.
///
/// This method was marked as obsolete on NLog 4.0 and it may be removed in a future release.
/// </remarks>
[Obsolete("Use ResumeLogging() instead. Marked obsolete on NLog 4.0")]
public void EnableLogging()
{
ResumeLogging();
}
/// <summary>
/// Decreases the log enable counter and if it reaches -1 the logs are disabled.
/// </summary>
/// <remarks>
/// Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater than
/// or equal to <see cref="SuspendLogging"/> calls.
/// </remarks>
/// <returns>An object that implements IDisposable whose Dispose() method re-enables logging.
/// To be used with C# <c>using ()</c> statement.</returns>
public IDisposable SuspendLogging()
{
lock (_syncRoot)
{
_logsEnabled--;
if (_logsEnabled == -1)
{
ReconfigExistingLoggers();
}
}
return new LogEnabler(this);
}
/// <summary>
/// Increases the log enable counter and if it reaches 0 the logs are disabled.
/// </summary>
/// <remarks>Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater
/// than or equal to <see cref="SuspendLogging"/> calls.</remarks>
public void ResumeLogging()
{
lock (_syncRoot)
{
_logsEnabled++;
if (_logsEnabled == 0)
{
ReconfigExistingLoggers();
}
}
}
/// <summary>
/// Returns <see langword="true" /> if logging is currently enabled.
/// </summary>
/// <returns>A value of <see langword="true" /> if logging is currently enabled,
/// <see langword="false"/> otherwise.</returns>
/// <remarks>Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater
/// than or equal to <see cref="SuspendLogging"/> calls.</remarks>
public bool IsLoggingEnabled()
{
return _logsEnabled >= 0;
}
/// <summary>
/// Raises the event when the configuration is reloaded.
/// </summary>
/// <param name="e">Event arguments.</param>
protected virtual void OnConfigurationChanged(LoggingConfigurationChangedEventArgs e)
{
ConfigurationChanged?.Invoke(this, e);
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD1_3
/// <summary>
/// Raises the event when the configuration is reloaded.
/// </summary>
/// <param name="e">Event arguments</param>
protected virtual void OnConfigurationReloaded(LoggingConfigurationReloadedEventArgs e)
{
ConfigurationReloaded?.Invoke(this, e);
}
internal void NotifyConfigurationReloaded(LoggingConfigurationReloadedEventArgs eventArgs)
{
OnConfigurationReloaded(eventArgs);
}
#endif
private bool GetTargetsByLevelForLogger(string name, List<LoggingRule> loggingRules, TargetWithFilterChain[] targetsByLevel, TargetWithFilterChain[] lastTargetsByLevel, bool[] suppressedLevels)
{
bool targetsFound = false;
foreach (LoggingRule rule in loggingRules)
{
if (!rule.NameMatches(name))
{
continue;
}
for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
if (i < GlobalThreshold.Ordinal || suppressedLevels[i] || !rule.IsLoggingEnabledForLevel(LogLevel.FromOrdinal(i)))
{
continue;
}
if (rule.Final)
suppressedLevels[i] = true;
foreach (Target target in rule.GetTargetsThreadSafe())
{
targetsFound = true;
var awf = new TargetWithFilterChain(target, rule.Filters, rule.DefaultFilterResult);
if (lastTargetsByLevel[i] != null)
{
lastTargetsByLevel[i].NextInChain = awf;
}
else
{
targetsByLevel[i] = awf;
}
lastTargetsByLevel[i] = awf;
}
}
// Recursively analyze the child rules.
if (rule.ChildRules.Count != 0)
{
targetsFound = GetTargetsByLevelForLogger(name, rule.GetChildRulesThreadSafe(), targetsByLevel, lastTargetsByLevel, suppressedLevels) || targetsFound;
}
}
for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
TargetWithFilterChain tfc = targetsByLevel[i];
tfc?.PrecalculateStackTraceUsage();
}
return targetsFound;
}
internal LoggerConfiguration GetConfigurationForLogger(string name, LoggingConfiguration configuration)
{
TargetWithFilterChain[] targetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
TargetWithFilterChain[] lastTargetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
bool[] suppressedLevels = new bool[LogLevel.MaxLevel.Ordinal + 1];
bool targetsFound = false;
if (configuration != null && IsLoggingEnabled())
{
//no "System.InvalidOperationException: Collection was modified"
var loggingRules = configuration.GetLoggingRulesThreadSafe();
targetsFound = GetTargetsByLevelForLogger(name, loggingRules, targetsByLevel, lastTargetsByLevel, suppressedLevels);
}
if (InternalLogger.IsDebugEnabled)
{
if (targetsFound)
{
InternalLogger.Debug("Targets for {0} by level:", name);
for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat(CultureInfo.InvariantCulture, "{0} =>", LogLevel.FromOrdinal(i));
for (TargetWithFilterChain afc = targetsByLevel[i]; afc != null; afc = afc.NextInChain)
{
sb.AppendFormat(CultureInfo.InvariantCulture, " {0}", afc.Target.Name);
if (afc.FilterChain.Count > 0)
{
sb.AppendFormat(CultureInfo.InvariantCulture, " ({0} filters)", afc.FilterChain.Count);
}
}
InternalLogger.Debug(sb.ToString());
}
}
else
{
InternalLogger.Debug("Targets not configured for logger: {0}", name);
}
}
#pragma warning disable 618
return new LoggerConfiguration(targetsByLevel, configuration != null && configuration.ExceptionLoggingOldStyle);
#pragma warning restore 618
}
/// <summary>
/// Currently this logfactory is disposing?
/// </summary>
private bool _isDisposing;
private void Close(TimeSpan flushTimeout)
{
if (_isDisposing)
{
return;
}
_isDisposing = true;
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD1_3
LoggerShutdown -= OnStopLogging;
ConfigurationReloaded = null; // Release event listeners
#endif
if (Monitor.TryEnter(_syncRoot, 500))
{
try
{
_configLoader.Dispose();
var oldConfig = _config;
if (_configLoaded && oldConfig != null)
{
CloseOldConfig(flushTimeout, oldConfig);
}
}
finally
{
Monitor.Exit(_syncRoot);
}
}
ConfigurationChanged = null; // Release event listeners
}
private void CloseOldConfig(TimeSpan flushTimeout, LoggingConfiguration oldConfig)
{
try
{
bool attemptClose = true;
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD1_3 && !MONO
if (flushTimeout != TimeSpan.Zero && !PlatformDetector.IsMono && !PlatformDetector.IsUnix)
{
// MONO (and friends) have a hard time with spinning up flush threads/timers during shutdown
ManualResetEvent flushCompleted = new ManualResetEvent(false);
oldConfig.FlushAllTargets((ex) => flushCompleted.Set());
attemptClose = flushCompleted.WaitOne(flushTimeout);
}
#endif
// Disable all loggers, so things become quiet
_config = null;
ReconfigExistingLoggers();
if (!attemptClose)
{
InternalLogger.Warn("Target flush timeout. One or more targets did not complete flush operation, skipping target close.");
}
else
{
// Flush completed within timeout, lets try and close down
oldConfig.Close();
OnConfigurationChanged(new LoggingConfigurationChangedEventArgs(null, oldConfig));
}
}
catch (Exception ex)
{
InternalLogger.Error(ex, "Error with close.");
}
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>True</c> to release both managed and unmanaged resources;
/// <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Close(TimeSpan.Zero);
}
}
internal void Shutdown()
{
InternalLogger.Info("Shutdown() called. Logger closing...");
if (!_isDisposing && _configLoaded)
{
lock (_syncRoot)
{
if (_isDisposing || !_configLoaded)
return;
Configuration = null;
_configLoaded = true; // Locked disabled state
ReconfigExistingLoggers(); // Disable all loggers, so things become quiet
}
}
InternalLogger.Info("Logger has been closed down.");
}
/// <summary>
/// Get file paths (including filename) for the possible NLog config files.
/// </summary>
/// <returns>The filepaths to the possible config file</returns>
public IEnumerable<string> GetCandidateConfigFilePaths()
{
if (_candidateConfigFilePaths != null)
{
return _candidateConfigFilePaths.AsReadOnly();
}
return _configLoader.GetDefaultCandidateConfigFilePaths();
}
/// <summary>
/// Overwrite the paths (including filename) for the possible NLog config files.
/// </summary>
/// <param name="filePaths">The filepaths to the possible config file</param>
public void SetCandidateConfigFilePaths(IEnumerable<string> filePaths)
{
_candidateConfigFilePaths = new List<string>();
if (filePaths != null)
{
_candidateConfigFilePaths.AddRange(filePaths);
}
}
/// <summary>
/// Clear the candidate file paths and return to the defaults.
/// </summary>
public void ResetCandidateConfigFilePath()
{
_candidateConfigFilePaths = null;
}
private Logger GetLogger(LoggerCacheKey cacheKey)
{
lock (_syncRoot)
{
Logger existingLogger = _loggerCache.Retrieve(cacheKey);
if (existingLogger != null)
{
// Logger is still in cache and referenced.
return existingLogger;
}
Logger newLogger;
if (cacheKey.ConcreteType != null && cacheKey.ConcreteType != typeof(Logger))
{
try
{
newLogger = CreateCustomLoggerType(cacheKey.ConcreteType);
if (newLogger == null)
{
// Creating default instance of logger if instance of specified type cannot be created.
newLogger = CreateDefaultLogger(ref cacheKey);
}
}
catch (Exception ex)
{
InternalLogger.Error(ex, "GetLogger / GetCurrentClassLogger. Cannot create instance of type '{0}'. It should have an default contructor.", cacheKey.ConcreteType);
if (ex.MustBeRethrown())
{
throw;
}
// Creating default instance of logger if instance of specified type cannot be created.
newLogger = CreateDefaultLogger(ref cacheKey);
}
}
else
{
newLogger = new Logger();
}
if (cacheKey.ConcreteType != null)
{
newLogger.Initialize(cacheKey.Name, GetConfigurationForLogger(cacheKey.Name, Configuration), this);
}
// TODO: Clarify what is the intention when cacheKey.ConcreteType = null.
// At the moment, a logger typeof(Logger) will be created but the ConcreteType
// will remain null and inserted into the cache.
// Should we set cacheKey.ConcreteType = typeof(Logger) for default loggers?
_loggerCache.InsertOrUpdate(cacheKey, newLogger);
return newLogger;
}
}
private Logger CreateCustomLoggerType(Type customLoggerType)
{
//creating instance of static class isn't possible, and also not wanted (it cannot inherited from Logger)
if (customLoggerType.IsStaticClass())
{
var errorMessage =
$"GetLogger / GetCurrentClassLogger is '{customLoggerType}' as loggerType is static class and should instead inherit from Logger";
InternalLogger.Error(errorMessage);
if (ThrowExceptions)
{
throw new NLogRuntimeException(errorMessage);
}
return null;
}
else
{
var instance = FactoryHelper.CreateInstance(customLoggerType);
var newLogger = instance as Logger;
if (newLogger == null)
{
//well, it's not a Logger, and we should return a Logger.
var errorMessage =
$"GetLogger / GetCurrentClassLogger got '{customLoggerType}' as loggerType doesn't inherit from Logger";
InternalLogger.Error(errorMessage);
if (ThrowExceptions)
{
throw new NLogRuntimeException(errorMessage);
}
return null;
}
return newLogger;
}
}
private static Logger CreateDefaultLogger(ref LoggerCacheKey cacheKey)
{
cacheKey = new LoggerCacheKey(cacheKey.Name, typeof(Logger));
var newLogger = new Logger();
return newLogger;
}
/// <summary>
/// Loads logging configuration from file (Currently only XML configuration files supported)
/// </summary>
/// <param name="configFile">Configuration file to be read</param>
/// <returns>LogFactory instance for fluent interface</returns>
public LogFactory LoadConfiguration(string configFile)
{
// TODO Remove explicit File-loading logic from LogFactory (Should handle environment without files)
if (_configLoader is LoggingConfigurationFileLoader configFileLoader)
{
Configuration = configFileLoader.Load(this, configFile);
}