-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLibLog.cs
More file actions
1981 lines (1774 loc) · 74.5 KB
/
LibLog.cs
File metadata and controls
1981 lines (1774 loc) · 74.5 KB
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 2014 Dominick Baier, Brock Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// ReSharper disable PossibleNullReferenceException
// Define LIBLOG_PORTABLE conditional compilation symbol for PCL compatibility
//
// Define LIBLOG_PUBLIC to enable ability to GET a logger (LogProvider.For<>() etc) from outside this library. NOTE:
// this can have unintendend consequences of consumers of your library using your library to resolve a logger. If the
// reason is because you want to open this functionality to other projects within your solution,
// consider [InternalVisibleTo] instead.
//
// Define LIBLOG_PROVIDERS_ONLY if your library provides its own logging API and you just want to use the
// LibLog providers internally to provide built in support for popular logging frameworks.
#pragma warning disable 1591
// If you copied this file manually, you need to change all "YourRootNameSpace" so not to clash with other libraries
// that use LibLog
#if LIBLOG_PROVIDERS_ONLY
namespace IdentityManager.Host.LibLog
#else
namespace IdentityManager.Host.Logging
#endif
{
using System.Collections.Generic;
#if LIBLOG_PROVIDERS_ONLY
using IdentityManager.Host.LibLog.LogProviders;
#else
using IdentityManager.Host.Logging.LogProviders;
#endif
using System;
#if !LIBLOG_PROVIDERS_ONLY
using System.Diagnostics;
using System.Runtime.CompilerServices;
#endif
#if LIBLOG_PROVIDERS_ONLY
internal
#else
public
#endif
delegate bool Logger(LogLevel logLevel, Func<string> messageFunc, Exception exception = null, params object[] formatParameters);
#if !LIBLOG_PROVIDERS_ONLY
/// <summary>
/// Simple interface that represent a logger.
/// </summary>
#if LIBLOG_PUBLIC
public
#else
internal
#endif
interface ILog
{
/// <summary>
/// Log a message the specified log level.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="messageFunc">The message function.</param>
/// <param name="exception">An optional exception.</param>
/// <param name="formatParameters">Optional format parameters for the message generated by the messagefunc. </param>
/// <returns>true if the message was logged. Otherwise false.</returns>
/// <remarks>
/// Note to implementers: the message func should not be called if the loglevel is not enabled
/// so as not to incur performance penalties.
///
/// To check IsEnabled call Log with only LogLevel and check the return value, no event will be written.
/// </remarks>
bool Log(LogLevel logLevel, Func<string> messageFunc, Exception exception = null, params object[] formatParameters );
}
#endif
/// <summary>
/// The log level.
/// </summary>
#if LIBLOG_PROVIDERS_ONLY
internal
#else
public
#endif
enum LogLevel
{
Trace,
Debug,
Info,
Warn,
Error,
Fatal
}
#if !LIBLOG_PROVIDERS_ONLY
#if LIBLOG_PUBLIC
public
#else
internal
#endif
static partial class LogExtensions
{
public static bool IsDebugEnabled(this ILog logger)
{
GuardAgainstNullLogger(logger);
return logger.Log(LogLevel.Debug, null);
}
public static bool IsErrorEnabled(this ILog logger)
{
GuardAgainstNullLogger(logger);
return logger.Log(LogLevel.Error, null);
}
public static bool IsFatalEnabled(this ILog logger)
{
GuardAgainstNullLogger(logger);
return logger.Log(LogLevel.Fatal, null);
}
public static bool IsInfoEnabled(this ILog logger)
{
GuardAgainstNullLogger(logger);
return logger.Log(LogLevel.Info, null);
}
public static bool IsTraceEnabled(this ILog logger)
{
GuardAgainstNullLogger(logger);
return logger.Log(LogLevel.Trace, null);
}
public static bool IsWarnEnabled(this ILog logger)
{
GuardAgainstNullLogger(logger);
return logger.Log(LogLevel.Warn, null);
}
public static void Debug(this ILog logger, Func<string> messageFunc)
{
GuardAgainstNullLogger(logger);
logger.Log(LogLevel.Debug, messageFunc);
}
public static void Debug(this ILog logger, string message)
{
if (logger.IsDebugEnabled())
{
logger.Log(LogLevel.Debug, message.AsFunc());
}
}
public static void DebugFormat(this ILog logger, string message, params object[] args)
{
if (logger.IsDebugEnabled())
{
logger.LogFormat(LogLevel.Debug, message, args);
}
}
public static void DebugException(this ILog logger, string message, Exception exception)
{
if (logger.IsDebugEnabled())
{
logger.Log(LogLevel.Debug, message.AsFunc(), exception);
}
}
public static void DebugException(this ILog logger, string message, Exception exception, params object[] formatParams)
{
if (logger.IsDebugEnabled())
{
logger.Log(LogLevel.Debug, message.AsFunc(), exception, formatParams);
}
}
public static void Error(this ILog logger, Func<string> messageFunc)
{
logger.Log(LogLevel.Error, messageFunc);
}
public static void Error(this ILog logger, string message)
{
if (logger.IsErrorEnabled())
{
logger.Log(LogLevel.Error, message.AsFunc());
}
}
public static void ErrorFormat(this ILog logger, string message, params object[] args)
{
if (logger.IsErrorEnabled())
{
logger.LogFormat(LogLevel.Error, message, args);
}
}
public static void ErrorException(this ILog logger, string message, Exception exception, params object[] formatParams)
{
if (logger.IsErrorEnabled())
{
logger.Log(LogLevel.Error, message.AsFunc(), exception, formatParams);
}
}
public static void Fatal(this ILog logger, Func<string> messageFunc)
{
logger.Log(LogLevel.Fatal, messageFunc);
}
public static void Fatal(this ILog logger, string message)
{
if (logger.IsFatalEnabled())
{
logger.Log(LogLevel.Fatal, message.AsFunc());
}
}
public static void FatalFormat(this ILog logger, string message, params object[] args)
{
if (logger.IsFatalEnabled())
{
logger.LogFormat(LogLevel.Fatal, message, args);
}
}
public static void FatalException(this ILog logger, string message, Exception exception, params object[] formatParams)
{
if (logger.IsFatalEnabled())
{
logger.Log(LogLevel.Fatal, message.AsFunc(), exception, formatParams);
}
}
public static void Info(this ILog logger, Func<string> messageFunc)
{
GuardAgainstNullLogger(logger);
logger.Log(LogLevel.Info, messageFunc);
}
public static void Info(this ILog logger, string message)
{
if (logger.IsInfoEnabled())
{
logger.Log(LogLevel.Info, message.AsFunc());
}
}
public static void InfoFormat(this ILog logger, string message, params object[] args)
{
if (logger.IsInfoEnabled())
{
logger.LogFormat(LogLevel.Info, message, args);
}
}
public static void InfoException(this ILog logger, string message, Exception exception, params object[] formatParams)
{
if (logger.IsInfoEnabled())
{
logger.Log(LogLevel.Info, message.AsFunc(), exception, formatParams);
}
}
public static void Trace(this ILog logger, Func<string> messageFunc)
{
GuardAgainstNullLogger(logger);
logger.Log(LogLevel.Trace, messageFunc);
}
public static void Trace(this ILog logger, string message)
{
if (logger.IsTraceEnabled())
{
logger.Log(LogLevel.Trace, message.AsFunc());
}
}
public static void TraceFormat(this ILog logger, string message, params object[] args)
{
if (logger.IsTraceEnabled())
{
logger.LogFormat(LogLevel.Trace, message, args);
}
}
public static void TraceException(this ILog logger, string message, Exception exception, params object[] formatParams)
{
if (logger.IsTraceEnabled())
{
logger.Log(LogLevel.Trace, message.AsFunc(), exception, formatParams);
}
}
public static void Warn(this ILog logger, Func<string> messageFunc)
{
GuardAgainstNullLogger(logger);
logger.Log(LogLevel.Warn, messageFunc);
}
public static void Warn(this ILog logger, string message)
{
if (logger.IsWarnEnabled())
{
logger.Log(LogLevel.Warn, message.AsFunc());
}
}
public static void WarnFormat(this ILog logger, string message, params object[] args)
{
if (logger.IsWarnEnabled())
{
logger.LogFormat(LogLevel.Warn, message, args);
}
}
public static void WarnException(this ILog logger, string message, Exception exception, params object[] formatParams)
{
if (logger.IsWarnEnabled())
{
logger.Log(LogLevel.Warn, message.AsFunc(), exception, formatParams);
}
}
// ReSharper disable once UnusedParameter.Local
private static void GuardAgainstNullLogger(ILog logger)
{
if (logger == null)
{
throw new ArgumentNullException("logger");
}
}
private static void LogFormat(this ILog logger, LogLevel logLevel, string message, params object[] args)
{
logger.Log(logLevel, message.AsFunc(), null, args);
}
// Avoid the closure allocation, see https://gist.github.com/AArnott/d285feef75c18f6ecd2b
private static Func<T> AsFunc<T>(this T value) where T : class
{
return value.Return;
}
private static T Return<T>(this T value)
{
return value;
}
}
#endif
/// <summary>
/// Represents a way to get a <see cref="ILog"/>
/// </summary>
#if LIBLOG_PROVIDERS_ONLY
internal
#else
public
#endif
interface ILogProvider
{
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <returns>The logger reference.</returns>
Logger GetLogger(string name);
/// <summary>
/// Opens a nested diagnostics context. Not supported in EntLib logging.
/// </summary>
/// <param name="message">The message to add to the diagnostics context.</param>
/// <returns>A disposable that when disposed removes the message from the context.</returns>
IDisposable OpenNestedContext(string message);
/// <summary>
/// Opens a mapped diagnostics context. Not supported in EntLib logging.
/// </summary>
/// <param name="key">A key.</param>
/// <param name="value">A value.</param>
/// <returns>A disposable that when disposed removes the map from the context.</returns>
IDisposable OpenMappedContext(string key, string value);
}
/// <summary>
/// Provides a mechanism to create instances of <see cref="ILog" /> objects.
/// </summary>
#if LIBLOG_PROVIDERS_ONLY
internal
#else
public
#endif
static class LogProvider
{
#if !LIBLOG_PROVIDERS_ONLY
/// <summary>
/// The disable logging environment variable. If the environment variable is set to 'true', then logging
/// will be disabled.
/// </summary>
public const string DisableLoggingEnvironmentVariable = "IdentityManager.Host_LIBLOG_DISABLE";
private const string NullLogProvider = "Current Log Provider is not set. Call SetCurrentLogProvider " +
"with a non-null value first.";
private static dynamic _currentLogProvider;
private static Action<ILogProvider> _onCurrentLogProviderSet;
static LogProvider()
{
IsDisabled = false;
}
/// <summary>
/// Sets the current log provider.
/// </summary>
/// <param name="logProvider">The log provider.</param>
public static void SetCurrentLogProvider(ILogProvider logProvider)
{
_currentLogProvider = logProvider;
RaiseOnCurrentLogProviderSet();
}
/// <summary>
/// Gets or sets a value indicating whether this is logging is disabled.
/// </summary>
/// <value>
/// <c>true</c> if logging is disabled; otherwise, <c>false</c>.
/// </value>
public static bool IsDisabled { get; set; }
/// <summary>
/// Sets an action that is invoked when a consumer of your library has called SetCurrentLogProvider. It is
/// important that hook into this if you are using child libraries (especially ilmerged ones) that are using
/// LibLog (or other logging abstraction) so you adapt and delegate to them.
/// <see cref="SetCurrentLogProvider"/>
/// </summary>
internal static Action<ILogProvider> OnCurrentLogProviderSet
{
set
{
_onCurrentLogProviderSet = value;
RaiseOnCurrentLogProviderSet();
}
}
internal static ILogProvider CurrentLogProvider
{
get
{
return _currentLogProvider;
}
}
/// <summary>
/// Gets a logger for the specified type.
/// </summary>
/// <typeparam name="T">The type whose name will be used for the logger.</typeparam>
/// <returns>An instance of <see cref="ILog"/></returns>
#if LIBLOG_PUBLIC
public
#else
internal
#endif
static ILog For<T>()
{
return GetLogger(typeof(T));
}
#if !LIBLOG_PORTABLE
/// <summary>
/// Gets a logger for the current class.
/// </summary>
/// <returns>An instance of <see cref="ILog"/></returns>
[MethodImpl(MethodImplOptions.NoInlining)]
#if LIBLOG_PUBLIC
public
#else
internal
#endif
static ILog GetCurrentClassLogger()
{
var stackFrame = new StackFrame(1, false);
return GetLogger(stackFrame.GetMethod().DeclaringType);
}
#endif
/// <summary>
/// Gets a logger for the specified type.
/// </summary>
/// <param name="type">The type whose name will be used for the logger.</param>
/// <returns>An instance of <see cref="ILog"/></returns>
#if LIBLOG_PUBLIC
public
#else
internal
#endif
static ILog GetLogger(Type type)
{
return GetLogger(type.FullName);
}
/// <summary>
/// Gets a logger with the specified name.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>An instance of <see cref="ILog"/></returns>
#if LIBLOG_PUBLIC
public
#else
internal
#endif
static ILog GetLogger(string name)
{
ILogProvider logProvider = CurrentLogProvider ?? ResolveLogProvider();
return logProvider == null
? NoOpLogger.Instance
: (ILog)new LoggerExecutionWrapper(logProvider.GetLogger(name), () => IsDisabled);
}
/// <summary>
/// Opens a nested diagnostics context.
/// </summary>
/// <param name="message">A message.</param>
/// <returns>An <see cref="IDisposable"/> that closes context when disposed.</returns>
#if LIBLOG_PUBLIC
public
#else
internal
#endif
static IDisposable OpenNestedContext(string message)
{
if(CurrentLogProvider == null)
{
throw new InvalidOperationException(NullLogProvider);
}
return CurrentLogProvider.OpenNestedContext(message);
}
/// <summary>
/// Opens a mapped diagnostics context.
/// </summary>
/// <param name="key">A key.</param>
/// <param name="value">A value.</param>
/// <returns>An <see cref="IDisposable"/> that closes context when disposed.</returns>
#if LIBLOG_PUBLIC
public
#else
internal
#endif
static IDisposable OpenMappedContext(string key, string value)
{
if (CurrentLogProvider == null)
{
throw new InvalidOperationException(NullLogProvider);
}
return CurrentLogProvider.OpenMappedContext(key, value);
}
#endif
#if LIBLOG_PROVIDERS_ONLY
private
#else
internal
#endif
delegate bool IsLoggerAvailable();
#if LIBLOG_PROVIDERS_ONLY
private
#else
internal
#endif
delegate ILogProvider CreateLogProvider();
#if LIBLOG_PROVIDERS_ONLY
private
#else
internal
#endif
static readonly List<Tuple<IsLoggerAvailable, CreateLogProvider>> LogProviderResolvers =
new List<Tuple<IsLoggerAvailable, CreateLogProvider>>
{
new Tuple<IsLoggerAvailable, CreateLogProvider>(SerilogLogProvider.IsLoggerAvailable, () => new SerilogLogProvider()),
new Tuple<IsLoggerAvailable, CreateLogProvider>(NLogLogProvider.IsLoggerAvailable, () => new NLogLogProvider()),
new Tuple<IsLoggerAvailable, CreateLogProvider>(Log4NetLogProvider.IsLoggerAvailable, () => new Log4NetLogProvider()),
new Tuple<IsLoggerAvailable, CreateLogProvider>(EntLibLogProvider.IsLoggerAvailable, () => new EntLibLogProvider()),
new Tuple<IsLoggerAvailable, CreateLogProvider>(LoupeLogProvider.IsLoggerAvailable, () => new LoupeLogProvider()),
};
#if !LIBLOG_PROVIDERS_ONLY
private static void RaiseOnCurrentLogProviderSet()
{
if (_onCurrentLogProviderSet != null)
{
_onCurrentLogProviderSet(_currentLogProvider);
}
}
#endif
internal static ILogProvider ResolveLogProvider()
{
try
{
foreach (var providerResolver in LogProviderResolvers)
{
if (providerResolver.Item1())
{
return providerResolver.Item2();
}
}
}
catch (Exception ex)
{
#if LIBLOG_PORTABLE
Debug.WriteLine(
#else
Console.WriteLine(
#endif
"Exception occured resolving a log provider. Logging for this assembly {0} is disabled. {1}",
typeof(LogProvider).GetAssemblyPortable().FullName,
ex);
}
return null;
}
#if !LIBLOG_PROVIDERS_ONLY
internal class NoOpLogger : ILog
{
internal static readonly NoOpLogger Instance = new NoOpLogger();
public bool Log(LogLevel logLevel, Func<string> messageFunc, Exception exception, params object[] formatParameters)
{
return false;
}
}
#endif
}
#if !LIBLOG_PROVIDERS_ONLY
internal class LoggerExecutionWrapper : ILog
{
private readonly Logger _logger;
private readonly Func<bool> _getIsDisabled;
internal const string FailedToGenerateLogMessage = "Failed to generate log message";
internal LoggerExecutionWrapper(Logger logger, Func<bool> getIsDisabled = null)
{
_logger = logger;
_getIsDisabled = getIsDisabled ?? (() => false);
}
internal Logger WrappedLogger
{
get { return _logger; }
}
public bool Log(LogLevel logLevel, Func<string> messageFunc, Exception exception = null, params object[] formatParameters)
{
#if LIBLOG_PORTABLE
if (_getIsDisabled())
{
return false;
}
#else
var envVar = Environment.GetEnvironmentVariable(LogProvider.DisableLoggingEnvironmentVariable);
if (_getIsDisabled() || (envVar != null && envVar.Equals("true", StringComparison.OrdinalIgnoreCase)))
{
return false;
}
#endif
if (messageFunc == null)
{
return _logger(logLevel, null);
}
Func<string> wrappedMessageFunc = () =>
{
try
{
return messageFunc();
}
catch (Exception ex)
{
Log(LogLevel.Error, () => FailedToGenerateLogMessage, ex);
}
return null;
};
return _logger(logLevel, wrappedMessageFunc, exception, formatParameters);
}
}
#endif
}
#if LIBLOG_PROVIDERS_ONLY
namespace IdentityManager.Host.LibLog.LogProviders
#else
namespace IdentityManager.Host.Logging.LogProviders
#endif
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
internal abstract class LogProviderBase : ILogProvider
{
protected delegate IDisposable OpenNdc(string message);
protected delegate IDisposable OpenMdc(string key, string value);
private readonly Lazy<OpenNdc> _lazyOpenNdcMethod;
private readonly Lazy<OpenMdc> _lazyOpenMdcMethod;
private static readonly IDisposable NoopDisposableInstance = new DisposableAction();
protected LogProviderBase()
{
_lazyOpenNdcMethod
= new Lazy<OpenNdc>(GetOpenNdcMethod);
_lazyOpenMdcMethod
= new Lazy<OpenMdc>(GetOpenMdcMethod);
}
public abstract Logger GetLogger(string name);
public IDisposable OpenNestedContext(string message)
{
return _lazyOpenNdcMethod.Value(message);
}
public IDisposable OpenMappedContext(string key, string value)
{
return _lazyOpenMdcMethod.Value(key, value);
}
protected virtual OpenNdc GetOpenNdcMethod()
{
return _ => NoopDisposableInstance;
}
protected virtual OpenMdc GetOpenMdcMethod()
{
return (_, __) => NoopDisposableInstance;
}
}
internal class NLogLogProvider : LogProviderBase
{
private readonly Func<string, object> _getLoggerByNameDelegate;
private static bool _providerIsAvailableOverride = true;
public NLogLogProvider()
{
if (!IsLoggerAvailable())
{
throw new InvalidOperationException("NLog.LogManager not found");
}
_getLoggerByNameDelegate = GetGetLoggerMethodCall();
}
public static bool ProviderIsAvailableOverride
{
get { return _providerIsAvailableOverride; }
set { _providerIsAvailableOverride = value; }
}
public override Logger GetLogger(string name)
{
return new NLogLogger(_getLoggerByNameDelegate(name)).Log;
}
public static bool IsLoggerAvailable()
{
return ProviderIsAvailableOverride && GetLogManagerType() != null;
}
protected override OpenNdc GetOpenNdcMethod()
{
Type ndcContextType = Type.GetType("NLog.NestedDiagnosticsContext, NLog");
MethodInfo pushMethod = ndcContextType.GetMethodPortable("Push", typeof(string));
ParameterExpression messageParam = Expression.Parameter(typeof(string), "message");
MethodCallExpression pushMethodCall = Expression.Call(null, pushMethod, messageParam);
return Expression.Lambda<OpenNdc>(pushMethodCall, messageParam).Compile();
}
protected override OpenMdc GetOpenMdcMethod()
{
Type mdcContextType = Type.GetType("NLog.MappedDiagnosticsContext, NLog");
MethodInfo setMethod = mdcContextType.GetMethodPortable("Set", typeof(string), typeof(string));
MethodInfo removeMethod = mdcContextType.GetMethodPortable("Remove", typeof(string));
ParameterExpression keyParam = Expression.Parameter(typeof(string), "key");
ParameterExpression valueParam = Expression.Parameter(typeof(string), "value");
MethodCallExpression setMethodCall = Expression.Call(null, setMethod, keyParam, valueParam);
MethodCallExpression removeMethodCall = Expression.Call(null, removeMethod, keyParam);
Action<string, string> set = Expression
.Lambda<Action<string, string>>(setMethodCall, keyParam, valueParam)
.Compile();
Action<string> remove = Expression
.Lambda<Action<string>>(removeMethodCall, keyParam)
.Compile();
return (key, value) =>
{
set(key, value);
return new DisposableAction(() => remove(key));
};
}
private static Type GetLogManagerType()
{
return Type.GetType("NLog.LogManager, NLog");
}
private static Func<string, object> GetGetLoggerMethodCall()
{
Type logManagerType = GetLogManagerType();
MethodInfo method = logManagerType.GetMethodPortable("GetLogger", typeof(string));
ParameterExpression nameParam = Expression.Parameter(typeof(string), "name");
MethodCallExpression methodCall = Expression.Call(null, method, nameParam);
return Expression.Lambda<Func<string, object>>(methodCall, nameParam).Compile();
}
internal class NLogLogger
{
private readonly dynamic _logger;
internal NLogLogger(dynamic logger)
{
_logger = logger;
}
public bool Log(LogLevel logLevel, Func<string> messageFunc, Exception exception, params object[] formatParameters)
{
if (messageFunc == null)
{
return IsLogLevelEnable(logLevel);
}
messageFunc = LogMessageFormatter.SimulateStructuredLogging(messageFunc, formatParameters);
if(exception != null)
{
return LogException(logLevel, messageFunc, exception);
}
switch (logLevel)
{
case LogLevel.Debug:
if (_logger.IsDebugEnabled)
{
_logger.Debug(messageFunc());
return true;
}
break;
case LogLevel.Info:
if (_logger.IsInfoEnabled)
{
_logger.Info(messageFunc());
return true;
}
break;
case LogLevel.Warn:
if (_logger.IsWarnEnabled)
{
_logger.Warn(messageFunc());
return true;
}
break;
case LogLevel.Error:
if (_logger.IsErrorEnabled)
{
_logger.Error(messageFunc());
return true;
}
break;
case LogLevel.Fatal:
if (_logger.IsFatalEnabled)
{
_logger.Fatal(messageFunc());
return true;
}
break;
default:
if (_logger.IsTraceEnabled)
{
_logger.Trace(messageFunc());
return true;
}
break;
}
return false;
}
private bool LogException(LogLevel logLevel, Func<string> messageFunc, Exception exception)
{
switch (logLevel)
{
case LogLevel.Debug:
if (_logger.IsDebugEnabled)
{
_logger.DebugException(messageFunc(), exception);
return true;
}
break;
case LogLevel.Info:
if (_logger.IsInfoEnabled)
{
_logger.InfoException(messageFunc(), exception);
return true;
}
break;
case LogLevel.Warn:
if (_logger.IsWarnEnabled)
{
_logger.WarnException(messageFunc(), exception);
return true;
}
break;
case LogLevel.Error:
if (_logger.IsErrorEnabled)
{
_logger.ErrorException(messageFunc(), exception);
return true;
}
break;
case LogLevel.Fatal:
if (_logger.IsFatalEnabled)
{
_logger.FatalException(messageFunc(), exception);
return true;
}
break;
default:
if (_logger.IsTraceEnabled)
{
_logger.TraceException(messageFunc(), exception);
return true;
}
break;
}
return false;
}
private bool IsLogLevelEnable(LogLevel logLevel)
{
switch (logLevel)
{
case LogLevel.Debug:
return _logger.IsDebugEnabled;
case LogLevel.Info:
return _logger.IsInfoEnabled;
case LogLevel.Warn:
return _logger.IsWarnEnabled;
case LogLevel.Error:
return _logger.IsErrorEnabled;
case LogLevel.Fatal:
return _logger.IsFatalEnabled;
default:
return _logger.IsTraceEnabled;
}
}
}
}
internal class Log4NetLogProvider : LogProviderBase
{
private readonly Func<string, object> _getLoggerByNameDelegate;
private static bool _providerIsAvailableOverride = true;
public Log4NetLogProvider()
{
if (!IsLoggerAvailable())
{
throw new InvalidOperationException("log4net.LogManager not found");
}
_getLoggerByNameDelegate = GetGetLoggerMethodCall();
}
public static bool ProviderIsAvailableOverride
{
get { return _providerIsAvailableOverride; }
set { _providerIsAvailableOverride = value; }
}
public override Logger GetLogger(string name)
{