-
Notifications
You must be signed in to change notification settings - Fork 468
Expand file tree
/
Copy pathLogHelper.cs
More file actions
729 lines (635 loc) · 37 KB
/
Copy pathLogHelper.cs
File metadata and controls
729 lines (635 loc) · 37 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.Linq;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Abstractions;
namespace Microsoft.IdentityModel.Logging
{
/// <summary>
/// Helper class for logging.
/// </summary>
public class LogHelper
{
/// <summary>
/// Gets or sets a logger to which logs will be written to.
/// </summary>
public static IIdentityLogger Logger { get; set; } = NullIdentityModelLogger.Instance;
/// <summary>
/// Indicates whether the log message header (contains library version, date/time, and PII debugging information) has been written.
/// </summary>
private static bool _isHeaderWritten;
/// <summary>
/// The log message that is shown when PII is off.
/// </summary>
private static string _piiOffLogMessage = "PII logging is OFF. See https://aka.ms/IdentityModel/PII for details. ";
/// <summary>
/// The log message that is shown when PII is on.
/// </summary>
private static string _piiOnLogMessage = "PII logging is ON, do not use in production. See https://aka.ms/IdentityModel/PII for details. ";
// internal for testing purposes only
internal static bool HeaderWritten
{
get { return _isHeaderWritten; }
set { _isHeaderWritten = value; }
}
/// <summary>
/// Gets a boolean indicating whether logging is enabled at the specified LogLevel.
/// </summary>
/// <param name="logLevel">The log level</param>
/// <param name="loggerContext">A <see cref="LoggerContext"/> that contains logging control including <see cref="ILogger"/>.</param>
/// <returns><see langword="true"/> if logging is enabled at the specified level; otherwise, <see langword="false"/>.</returns>
internal static bool IsEnabled(LogLevel logLevel, LoggerContext loggerContext)
{
return loggerContext?.Logger?.IsEnabled(logLevel) ?? false;
}
/// <summary>
/// Gets whether logging is enabled at the specified <see cref="EventLogLevel"/>."/>
/// </summary>
/// <param name="level">The log level</param>
/// <returns><see langword="true"/> if logging is enabled at the specified level; otherwise, <see langword="false"/>.</returns>
public static bool IsEnabled(EventLogLevel level) =>
Logger.IsEnabled(level) ||
IdentityModelEventSource.Logger.IsEnabled(EventLogLevelToEventLevel(level), EventKeywords.All);
/// <summary>
/// Logs an exception using the event source logger and returns new <see cref="ArgumentNullException"/> exception.
/// </summary>
/// <param name="argument">argument that is null or empty.</param>
/// <remarks>EventLevel is set to Error.</remarks>
public static ArgumentNullException LogArgumentNullException(string argument)
{
return LogArgumentException<ArgumentNullException>(EventLevel.Error, argument, "IDX10000: The parameter '{0}' cannot be a 'null' or an empty object. ", argument);
}
/// <summary>
/// Logs an exception using the event source logger and returns new typed exception.
/// </summary>
/// <param name="message">message to log.</param>
/// <remarks>EventLevel is set to Error.</remarks>
public static T LogException<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(string message) where T : Exception
{
return LogException<T>(EventLevel.Error, null, message, null);
}
/// <summary>
/// Logs an argument exception using the event source logger and returns new typed exception.
/// </summary>
/// <param name="argumentName">Identifies the argument whose value generated the ArgumentException.</param>
/// <param name="message">message to log.</param>
/// <remarks>EventLevel is set to Error.</remarks>
public static T LogArgumentException<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(string argumentName, string message) where T : ArgumentException
{
return LogArgumentException<T>(EventLevel.Error, argumentName, null, message, null);
}
/// <summary>
/// Logs an exception using the event source logger and returns new typed exception.
/// </summary>
/// <param name="format">Format string of the log message.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <remarks>EventLevel is set to Error.</remarks>
public static T LogException<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(string format, params object[] args) where T : Exception
{
return LogException<T>(EventLevel.Error, null, format, args);
}
/// <summary>
/// Logs an argument exception using the event source logger and returns new typed exception.
/// </summary>
/// <param name="argumentName">Identifies the argument whose value generated the ArgumentException.</param>
/// <param name="format">Format string of the log message.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <remarks>EventLevel is set to Error.</remarks>
public static T LogArgumentException<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(string argumentName, string format, params object[] args) where T : ArgumentException
{
return LogArgumentException<T>(EventLevel.Error, argumentName, null, format, args);
}
/// <summary>
/// Logs an exception using the event source logger and returns new typed exception.
/// </summary>
/// <param name="innerException">the inner <see cref="Exception"/> to be added to the outer exception.</param>
/// <param name="message">message to log.</param>
/// <remarks>EventLevel is set to Error.</remarks>
public static T LogException<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(Exception innerException, string message) where T : Exception
{
return LogException<T>(EventLevel.Error, innerException, message, null);
}
/// <summary>
/// Logs an argument exception using the event source logger and returns new typed exception.
/// </summary>
/// <param name="argumentName">Identifies the argument whose value generated the ArgumentException.</param>
/// <param name="innerException">the inner <see cref="Exception"/> to be added to the outer exception.</param>
/// <param name="message">message to log.</param>
/// <remarks>EventLevel is set to Error.</remarks>
public static T LogArgumentException<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(string argumentName, Exception innerException, string message) where T : ArgumentException
{
return LogArgumentException<T>(EventLevel.Error, argumentName, innerException, message, null);
}
/// <summary>
/// Logs an exception using the event source logger and returns new typed exception.
/// </summary>
/// <param name="innerException">the inner <see cref="Exception"/> to be added to the outer exception.</param>
/// <param name="format">Format string of the log message.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <remarks>EventLevel is set to Error.</remarks>
public static T LogException<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(Exception innerException, string format, params object[] args) where T : Exception
{
return LogException<T>(EventLevel.Error, innerException, format, args);
}
/// <summary>
/// Logs an argument exception using the event source logger and returns new typed exception.
/// </summary>
/// <param name="argumentName">Identifies the argument whose value generated the ArgumentException.</param>
/// <param name="innerException">the inner <see cref="Exception"/> to be added to the outer exception.</param>
/// <param name="format">Format string of the log message.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <remarks>EventLevel is set to Error.</remarks>
public static T LogArgumentException<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(string argumentName, Exception innerException, string format, params object[] args) where T : ArgumentException
{
return LogArgumentException<T>(EventLevel.Error, argumentName, innerException, format, args);
}
/// <summary>
/// Logs an exception using the event source logger and returns new typed exception.
/// </summary>
/// <param name="eventLevel">Identifies the level of an event to be logged.</param>
/// <param name="message">message to log.</param>
public static T LogException<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(EventLevel eventLevel, string message) where T : Exception
{
return LogException<T>(eventLevel, null, message, null);
}
/// <summary>
/// Logs an argument exception using the event source logger and returns new typed exception.
/// </summary>
/// <param name="eventLevel">Identifies the level of an event to be logged.</param>
/// <param name="argumentName">Identifies the argument whose value generated the ArgumentException.</param>
/// <param name="message">message to log.</param>
public static T LogArgumentException<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(EventLevel eventLevel, string argumentName, string message) where T : ArgumentException
{
return LogArgumentException<T>(eventLevel, argumentName, null, message, null);
}
/// <summary>
/// Logs an exception using the event source logger and returns new typed exception.
/// </summary>
/// <param name="eventLevel">Identifies the level of an event to be logged.</param>
/// <param name="format">Format string of the log message.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
public static T LogException<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(EventLevel eventLevel, string format, params object[] args) where T : Exception
{
return LogException<T>(eventLevel, null, format, args);
}
/// <summary>
/// Logs an argument exception using the event source logger and returns new typed exception.
/// </summary>
/// <param name="eventLevel">Identifies the level of an event to be logged.</param>
/// <param name="argumentName">Identifies the argument whose value generated the ArgumentException.</param>
/// <param name="format">Format string of the log message.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
public static T LogArgumentException<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(EventLevel eventLevel, string argumentName, string format, params object[] args) where T : ArgumentException
{
return LogArgumentException<T>(eventLevel, argumentName, null, format, args);
}
/// <summary>
/// Logs an exception using the event source logger and returns new typed exception.
/// </summary>
/// <param name="eventLevel">Identifies the level of an event to be logged.</param>
/// <param name="innerException">the inner <see cref="Exception"/> to be added to the outer exception.</param>
/// <param name="message">message to log.</param>
public static T LogException<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(EventLevel eventLevel, Exception innerException, string message) where T : Exception
{
return LogException<T>(eventLevel, innerException, message, null);
}
/// <summary>
/// Logs an argument exception using the event source logger and returns new typed exception.
/// </summary>
/// <param name="eventLevel">Identifies the level of an event to be logged.</param>
/// <param name="argumentName">Identifies the argument whose value generated the ArgumentException.</param>
/// <param name="innerException">the inner <see cref="Exception"/> to be added to the outer exception.</param>
/// <param name="message">message to log.</param>
public static T LogArgumentException<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(EventLevel eventLevel, string argumentName, Exception innerException, string message) where T : ArgumentException
{
return LogArgumentException<T>(eventLevel, argumentName, innerException, message, null);
}
/// <summary>
/// Logs an exception using the event source logger and returns new typed exception.
/// </summary>
/// <param name="eventLevel">Identifies the level of an event to be logged.</param>
/// <param name="innerException">the inner <see cref="Exception"/> to be added to the outer exception.</param>
/// <param name="format">Format string of the log message.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
public static T LogException<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(EventLevel eventLevel, Exception innerException, string format, params object[] args) where T : Exception
{
return LogExceptionImpl<T>(eventLevel, null, innerException, format, args);
}
/// <summary>
/// Logs an argument exception using the event source logger and returns new typed exception.
/// </summary>
/// <param name="eventLevel">Identifies the level of an event to be logged.</param>
/// <param name="argumentName">Identifies the argument whose value generated the ArgumentException.</param>
/// <param name="innerException">the inner <see cref="Exception"/> to be added to the outer exception.</param>
/// <param name="format">Format string of the log message.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
public static T LogArgumentException<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(EventLevel eventLevel, string argumentName, Exception innerException, string format, params object[] args) where T : ArgumentException
{
return LogExceptionImpl<T>(eventLevel, argumentName, innerException, format, args);
}
/// <summary>
/// Logs an exception using the event source logger.
/// </summary>
/// <param name="exception">The exception to log.</param>
public static Exception LogExceptionMessage(Exception exception)
{
return LogExceptionMessage(EventLevel.Error, exception);
}
/// <summary>
/// Logs an exception using the event source logger.
/// </summary>
/// <param name="eventLevel">Identifies the level of an event to be logged.</param>
/// <param name="exception">The exception to log.</param>
public static Exception LogExceptionMessage(EventLevel eventLevel, Exception exception)
{
if (exception == null)
return null;
if (IdentityModelEventSource.Logger.IsEnabled(eventLevel, EventKeywords.All))
IdentityModelEventSource.Logger.Write(eventLevel, exception.InnerException, exception.Message);
EventLogLevel eventLogLevel = EventLevelToEventLogLevel(eventLevel);
if (Logger.IsEnabled(eventLogLevel))
Logger.Log(WriteEntry(eventLogLevel, exception.InnerException, exception.Message));
return exception;
}
/// <summary>
/// Logs an exception using the listeners that have been enabled.
/// </summary>
/// <param name="exception">The exception to log.</param>
/// <param name="loggerContext">The <see cref="LoggerContext"/> contains information useful for logging and debugging.</param>
public static Exception LogExceptionMessage(Exception exception, LoggerContext loggerContext)
{
if (exception == null)
return null;
LogExceptionMessage(exception);
if (loggerContext?.Logger == null)
return exception;
if (!loggerContext.Logger.IsEnabled(LogLevel.Error))
return exception;
LogEntry entry = WriteEntry(
EventLogLevel.Error,
exception.InnerException,
exception.Message,
loggerContext.CorrelationId ?? loggerContext.ActivityId.ToString(),
exception.Message,
null);
Log(entry, loggerContext.Logger);
return exception;
}
/// <summary>
/// Logs an information event.
/// </summary>
/// <param name="message">The log message.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
public static void LogInformation(string message, params object[] args)
{
if (IdentityModelEventSource.Logger.IsEnabled(EventLevel.Informational, EventKeywords.All))
IdentityModelEventSource.Logger.WriteInformation(message, args);
if (Logger.IsEnabled(EventLogLevel.Informational))
Logger.Log(WriteEntry(EventLogLevel.Informational, null, message, null, args));
}
/// <summary>
/// Logs at the information level to the listeners that have been enabled.
/// </summary>
/// <param name="message">The log message.</param>
/// <param name="loggerContext">A <see cref="LoggerContext"/> that contains logging control including <see cref="ILogger"/>.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
public static void LogInformation(string message, LoggerContext loggerContext, params object[] args)
{
LogInformation(message, args);
if (loggerContext?.Logger == null)
return;
if (!loggerContext.Logger.IsEnabled(LogLevel.Information))
return;
LogEntry entry = WriteEntry(
EventLevelToEventLogLevel(EventLevel.Informational),
null,
message,
loggerContext.CorrelationId ?? loggerContext.ActivityId.ToString(),
null);
Log(entry, loggerContext.Logger);
}
/// <summary>
/// Logs a verbose event.
/// </summary>
/// <param name="message">The log message.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
public static void LogVerbose(string message, params object[] args)
{
if (IdentityModelEventSource.Logger.IsEnabled(EventLevel.Verbose, EventKeywords.All))
IdentityModelEventSource.Logger.WriteVerbose(message, args);
if (Logger.IsEnabled(EventLogLevel.Verbose))
Logger.Log(WriteEntry(EventLogLevel.Verbose, null, message, null, args));
}
/// <summary>
/// Logs at the verbose level to the listeners that have been enabled.
/// </summary>
/// <param name="message">The log message.</param>
/// <param name="loggerContext">A <see cref="LoggerContext"/> that contains logging control including <see cref="ILogger"/>.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
public static void LogVerbose(string message, LoggerContext loggerContext, params object[] args)
{
LogVerbose(message, args);
if (loggerContext?.Logger == null)
return;
if (!loggerContext.Logger.IsEnabled(LogLevel.Debug))
return;
LogEntry entry = WriteEntry(
EventLogLevel.Verbose,
null,
message,
loggerContext.CorrelationId ?? loggerContext.ActivityId.ToString(),
null);
Log(entry, loggerContext.Logger);
}
/// <summary>
/// Logs a warning event.
/// </summary>
/// <param name="message">The log message.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
public static void LogWarning(string message, params object[] args)
{
if (IdentityModelEventSource.Logger.IsEnabled(EventLevel.Warning, EventKeywords.All))
IdentityModelEventSource.Logger.WriteWarning(message, args);
if (Logger.IsEnabled(EventLogLevel.Warning))
Logger.Log(WriteEntry(EventLogLevel.Warning, null, message, null, args));
}
/// <summary>
/// Logs at the warning level to the listeners that have been enabled.
/// </summary>
/// <param name="message">The log message.</param>
/// <param name="loggerContext">A <see cref="LoggerContext"/> that contains logging control including <see cref="ILogger"/>.</param>
public static void LogWarning(string message, LoggerContext loggerContext)
{
LogWarning(message, loggerContext, null);
}
/// <summary>
/// Logs at the warning level to the listeners that have been enabled.
/// </summary>
/// <param name="message">The log message.</param>
/// <param name="loggerContext">A <see cref="LoggerContext"/> that contains logging control including <see cref="ILogger"/>.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
public static void LogWarning(string message, LoggerContext loggerContext, params object[] args)
{
LogWarning(message, args);
if (loggerContext?.Logger == null)
return;
if (!loggerContext.Logger.IsEnabled(LogLevel.Warning))
return;
LogEntry entry = WriteEntry(
EventLogLevel.Warning,
null,
message,
loggerContext.CorrelationId ?? loggerContext.ActivityId.ToString(),
null);
Log(entry, loggerContext.Logger);
}
/// <summary>
/// Logs an exception using the event source logger and returns new typed exception.
/// </summary>
/// <param name="eventLevel">Identifies the level of an event to be logged.</param>
/// <param name="argumentName">Identifies the argument whose value generated the ArgumentException.</param>
/// <param name="innerException">the inner <see cref="Exception"/> to be added to the outer exception.</param>
/// <param name="format">Format string of the log message.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
private static T LogExceptionImpl<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(EventLevel eventLevel, string argumentName, Exception innerException, string format, params object[] args) where T : Exception
{
string message;
if (args != null)
message = string.Format(CultureInfo.InvariantCulture, format, args);
else
message = format;
if (IdentityModelEventSource.Logger.IsEnabled(eventLevel, EventKeywords.All))
IdentityModelEventSource.Logger.Write(eventLevel, innerException, message);
EventLogLevel eventLogLevel = EventLevelToEventLogLevel(eventLevel);
if (Logger.IsEnabled(eventLogLevel))
Logger.Log(WriteEntry(eventLogLevel, innerException, message));
if (innerException != null)
{
if (string.IsNullOrEmpty(argumentName))
return (T)Activator.CreateInstance(typeof(T), message, innerException);
else
return (T)Activator.CreateInstance(typeof(T), argumentName, message, innerException);
}
else
{
if (string.IsNullOrEmpty(argumentName))
return (T)Activator.CreateInstance(typeof(T), message);
else
return (T)Activator.CreateInstance(typeof(T), argumentName, message);
}
}
private static EventLogLevel EventLevelToEventLogLevel(EventLevel eventLevel) =>
(uint)(int)eventLevel <= 5 ? (EventLogLevel)eventLevel : EventLogLevel.Error;
private static EventLevel EventLogLevelToEventLevel(EventLogLevel eventLevel) =>
(uint)(int)eventLevel <= 5 ? (EventLevel)eventLevel : EventLevel.Error;
/// <summary>
/// Formats the string using InvariantCulture
/// </summary>
/// <param name="format">Format string.</param>
/// <param name="args">Format arguments.</param>
/// <returns>Formatted string.</returns>
public static string FormatInvariant(string format, params object[] args)
{
if (format == null)
return string.Empty;
if (args == null)
return format;
if (!IdentityModelEventSource.ShowPII)
return string.Format(CultureInfo.InvariantCulture, format, args.Select(RemovePII).ToArray());
else
return string.Format(CultureInfo.InvariantCulture, format, args.Select(SanitizeSecurityArtifact).ToArray());
}
private static object SanitizeSecurityArtifact(object arg)
{
if (arg == null)
return "null";
if (IdentityModelEventSource.LogCompleteSecurityArtifact && arg is ISafeLogSecurityArtifact)
return (arg as ISafeLogSecurityArtifact).UnsafeToString();
else if (arg is ISafeLogSecurityArtifact)
{
// We may later add a further flag which would log a best effort scrubbing of an artifact. E.g. JsonWebToken tries to remove the signature
// in the current implementation. Another flag may be added in the future to allow this middle path but for now, LogCompleteSecurityArtifact
// must be logged to emit any token part (other than specific claim values).
return string.Format(CultureInfo.InvariantCulture, IdentityModelEventSource.HiddenSecurityArtifactString, arg?.GetType().ToString() ?? "Null");
}
// If it's not a ISafeLogSecurityArtifact then just return the object which will be converted to string.
// It's possible a raw string will contain a security artifact and be exposed here but the alternative is to scrub all objects
// which defeats the purpose of the ShowPII flag.
return arg;
}
private static string RemovePII(object arg)
{
if (arg is Exception ex && IsCustomException(ex))
return ex.ToString();
if (arg is NonPII)
return arg.ToString();
return string.Format(CultureInfo.InvariantCulture, IdentityModelEventSource.HiddenPIIString, arg?.GetType().ToString() ?? "Null");
}
internal static bool IsCustomException(Exception ex)
{
return ex.GetType().FullName.StartsWith("Microsoft.IdentityModel.", StringComparison.Ordinal);
}
/// <summary>
/// Marks a log message argument (<paramref name="arg"/>) as NonPII.
/// </summary>
/// <param name="arg">A log message argument to be marked as NonPII.</param>
/// <returns>An argument marked as NonPII.</returns>
/// <remarks>
/// Marking an argument as NonPII in <see cref="LogHelper.FormatInvariant"/> calls will result in logging
/// that argument in cleartext, regardless of the <see cref="IdentityModelEventSource.ShowPII"/> flag value.
/// </remarks>
public static object MarkAsNonPII(object arg)
{
return new NonPII(arg);
}
/// <summary>
/// Marks a log message argument (<paramref name="arg"/>) as SecurityArtifact.
/// </summary>
/// <param name="arg">A log message argument to be marked as SecurityArtifact.</param>
/// <param name="callback">A callback function to log the security artifact safely.</param>
/// <returns>An argument marked as SecurityArtifact.</returns>
/// <remarks>
/// Since even the payload may sometimes contain security artifacts, naïve disarm algorithms such as removing signatures
/// will not work. For now the <paramref name="callback"/> will only be leveraged if
/// <see cref="IdentityModelEventSource.LogCompleteSecurityArtifact"/> is set and no unsafe callback is provided. Future changes
/// may introduce a support for best effort disarm logging.
/// </remarks>
public static object MarkAsSecurityArtifact(object arg, Func<object, string> callback)
{
return new SecurityArtifact(arg, callback);
}
/// <summary>
/// Marks a log message argument (<paramref name="arg"/>) as SecurityArtifact.
/// </summary>
/// <param name="arg">A log message argument to be marked as SecurityArtifact.</param>
/// <param name="callback">A callback function to log the security artifact safely.</param>
/// <param name="callbackUnsafe">A callback function to log the security artifact without scrubbing.</param>
/// <returns>An argument marked as SecurityArtifact.</returns>
/// <exception cref="ArgumentNullException">if <paramref name="callback"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="callbackUnsafe"/> is null.</exception>
/// <remarks>
/// Since even the payload may sometimes contain security artifacts, naïve disarm algorithms such as removing signatures
/// will not work. For now the <paramref name="callback"/> is currently unused. Future changes
/// may introduce a support for best effort disarm logging which will leverage <paramref name="callback"/>.
/// </remarks>
public static object MarkAsSecurityArtifact(object arg, Func<object, string> callback, Func<object, string> callbackUnsafe)
{
return new SecurityArtifact(arg, callback, callbackUnsafe);
}
/// <summary>
/// Marks a log message argument (<paramref name="arg"/>) as SecurityArtifact.
/// </summary>
/// <param name="arg">A log message argument to be marked as SecurityArtifact.</param>
/// <param name="callbackUnsafe">A callback function to log the security artifact without scrubbing.</param>
/// <returns>An argument marked as SecurityArtifact.</returns>
/// <exception cref="ArgumentNullException">if <paramref name="callbackUnsafe"/> is null.</exception>
public static object MarkAsUnsafeSecurityArtifact(object arg, Func<object, string> callbackUnsafe)
{
return new SecurityArtifact(arg, SecurityArtifact.UnknownSafeTokenCallback, callbackUnsafe);
}
/// <summary>
/// Creates a <see cref="LogEntry"/> by using the provided event level, exception argument, string argument and arguments list.
/// </summary>
/// <param name="eventLogLevel"><see cref="EventLogLevel"/></param>
/// <param name="innerException"><see cref="Exception"/></param>
/// <param name="message">The log message.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
private static LogEntry WriteEntry(
EventLogLevel eventLogLevel,
Exception innerException,
string message,
params object[] args)
{
return WriteEntry(eventLogLevel, innerException, message, (string)null, args);
}
/// <summary>
/// Creates a <see cref="LogEntry"/> by using the provided event level, exception argument, string argument and arguments list.
/// </summary>
/// <param name="eventLogLevel"><see cref="EventLogLevel"/></param>
/// <param name="innerException"><see cref="Exception"/></param>
/// <param name="message">The log message.</param>
/// <param name="correlationId">The CorrelationId is set by caller to coordinate logs between services.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
private static LogEntry WriteEntry(
EventLogLevel eventLogLevel,
Exception innerException,
string message,
string correlationId,
params object[] args)
{
if (string.IsNullOrEmpty(message))
return null;
if (innerException != null)
{
// if PII is turned off and 'innerException' is a System exception only display the exception type
if (!IdentityModelEventSource.ShowPII && !LogHelper.IsCustomException(innerException))
message = string.Format(CultureInfo.InvariantCulture, "Message: {0}, InnerException: {1}. ", message, innerException.GetType());
else // otherwise it's safe to display the entire exception message
message = string.Format(CultureInfo.InvariantCulture, "Message: {0}, InnerException: {1}. ", message, innerException.Message);
}
message = args == null ? message : FormatInvariant(message, args);
LogEntry entry = new LogEntry();
entry.EventLogLevel = eventLogLevel;
entry.CorrelationId = correlationId;
// Prefix header (library version, DateTime, whether PII is ON/OFF) to the first message logged by Wilson.
if (!_isHeaderWritten)
{
entry.Message = (correlationId == null) ?
string.Format(
CultureInfo.InvariantCulture,
"Microsoft.IdentityModel Version: {0}. Date {1}. {2} Message: {3}",
typeof(IdentityModelEventSource).Assembly.GetName().Version.ToString(),
DateTime.UtcNow,
IdentityModelEventSource.ShowPII ? _piiOnLogMessage : _piiOffLogMessage,
Environment.NewLine + message) :
string.Format(
CultureInfo.InvariantCulture,
"Microsoft.IdentityModel Version: {0}. Date {1}. {2} Message: {3}, CorrelationId: {4}.",
typeof(IdentityModelEventSource).Assembly.GetName().Version.ToString(),
DateTime.UtcNow,
IdentityModelEventSource.ShowPII ? _piiOnLogMessage : _piiOffLogMessage,
Environment.NewLine + message,
correlationId);
_isHeaderWritten = true;
}
else
entry.Message = (correlationId == null) ?
message :
string.Format(CultureInfo.InvariantCulture, "{0}, CorrelationId: {1}.", message, correlationId);
return entry;
}
private static void Log(LogEntry entry, ILogger logger)
{
if (entry != null)
{
switch (entry.EventLogLevel)
{
case EventLogLevel.Critical:
logger.LogCritical(entry.Message);
break;
case EventLogLevel.Error:
logger.LogError(entry.Message);
break;
case EventLogLevel.Warning:
logger.LogWarning(entry.Message);
break;
case EventLogLevel.Informational:
logger.LogInformation(entry.Message);
break;
case EventLogLevel.Verbose:
logger.LogDebug(entry.Message);
break;
case EventLogLevel.LogAlways:
logger.LogTrace(entry.Message);
break;
default:
break;
}
}
}
}
}