-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
LogEventInfo.cs
771 lines (698 loc) · 31.4 KB
/
LogEventInfo.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
//
// Copyright (c) 2004-2021 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.ComponentModel;
using System.Diagnostics;
using System.Threading;
using JetBrains.Annotations;
using NLog.Common;
using NLog.Internal;
using NLog.Layouts;
using NLog.MessageTemplates;
using NLog.Time;
/// <summary>
/// Represents the logging event.
/// </summary>
public class LogEventInfo
{
/// <summary>
/// Gets the date of the first log event created.
/// </summary>
public static readonly DateTime ZeroDate = DateTime.UtcNow;
private static int globalSequenceId;
/// <summary>
/// The formatted log message.
/// </summary>
private string _formattedMessage;
/// <summary>
/// The log message including any parameter placeholders
/// </summary>
private string _message;
private object[] _parameters;
private IFormatProvider _formatProvider;
private LogMessageFormatter _messageFormatter;
private IDictionary<Layout, object> _layoutCache;
private PropertiesDictionary _properties;
private int _sequenceId;
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
public LogEventInfo()
{
TimeStamp = TimeSource.Current.Time;
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param>
/// <param name="message">Log message including parameter placeholders.</param>
public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message)
: this(level, loggerName, null, message, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param>
/// <param name="message">Log message including parameter placeholders.</param>
/// <param name="messageTemplateParameters">Already parsed message template parameters.</param>
public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message, IList<MessageTemplateParameter> messageTemplateParameters)
: this(level, loggerName, null, message, null, null)
{
if (messageTemplateParameters != null)
{
var messagePropertyCount = messageTemplateParameters.Count;
if (messagePropertyCount > 0)
{
var messageProperties = new MessageTemplateParameter[messagePropertyCount];
for (int i = 0; i < messagePropertyCount; ++i)
messageProperties[i] = messageTemplateParameters[i];
_properties = new PropertiesDictionary(messageProperties);
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param>
/// <param name="formattedMessage">Pre-formatted log message for ${message}.</param>
/// <param name="messageTemplate">Log message-template including parameter placeholders for ${message:raw=true}.</param>
/// <param name="messageTemplateParameters">Already parsed message template parameters.</param>
public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string formattedMessage, [Localizable(false)] string messageTemplate, IList<MessageTemplateParameter> messageTemplateParameters)
: this(level, loggerName, messageTemplate, messageTemplateParameters)
{
_formattedMessage = formattedMessage;
_messageFormatter = (l) => l._formattedMessage ?? l.Message ?? string.Empty;
}
#if !NET35
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param>
/// <param name="message">Log message.</param>
/// <param name="eventProperties">List of event-properties</param>
public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message, IReadOnlyList<KeyValuePair<object, object>> eventProperties)
: this(level, loggerName, null, message, null, null)
{
if (eventProperties?.Count > 0)
{
_properties = new PropertiesDictionary(eventProperties);
}
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">Log message including parameter placeholders.</param>
/// <param name="parameters">Parameter array.</param>
public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters)
: this(level, loggerName, formatProvider, message, parameters, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">Log message including parameter placeholders.</param>
/// <param name="parameters">Parameter array.</param>
/// <param name="exception">Exception information.</param>
public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters, Exception exception)
: this()
{
Level = level;
LoggerName = loggerName;
_formatProvider = formatProvider;
_message = message;
Parameters = parameters;
Exception = exception;
}
/// <summary>
/// Gets the unique identifier of log event which is automatically generated
/// and monotonously increasing.
/// </summary>
// ReSharper disable once InconsistentNaming
public int SequenceID
{
get
{
if (_sequenceId == 0)
Interlocked.CompareExchange(ref _sequenceId, Interlocked.Increment(ref globalSequenceId), 0);
return _sequenceId;
}
}
/// <summary>
/// Gets or sets the timestamp of the logging event.
/// </summary>
public DateTime TimeStamp { get; set; }
/// <summary>
/// Gets or sets the level of the logging event.
/// </summary>
public LogLevel Level { get; set; }
[CanBeNull] internal CallSiteInformation CallSiteInformation { get; private set; }
[NotNull]
internal CallSiteInformation GetCallSiteInformationInternal() { return CallSiteInformation ?? (CallSiteInformation = new CallSiteInformation()); }
/// <summary>
/// Gets a value indicating whether stack trace has been set for this event.
/// </summary>
public bool HasStackTrace => CallSiteInformation?.StackTrace != null;
/// <summary>
/// Obsolete and replaced by <see cref="LogEventInfo.CallerMemberName"/> or ${callsite} with NLog v5.3.
///
/// Gets the stack frame of the method that did the logging.
/// </summary>
[Obsolete("Instead use ${callsite} or CallerMemberName. Marked obsolete on NLog 5.3")]
public StackFrame UserStackFrame => CallSiteInformation?.UserStackFrame;
/// <summary>
/// Gets the number index of the stack frame that represents the user
/// code (not the NLog code).
/// </summary>
public int UserStackFrameNumber => CallSiteInformation?.UserStackFrameNumberLegacy ?? CallSiteInformation?.UserStackFrameNumber ?? 0;
/// <summary>
/// Gets the entire stack trace.
/// </summary>
public StackTrace StackTrace => CallSiteInformation?.StackTrace;
/// <summary>
/// Gets the callsite class name
/// </summary>
public string CallerClassName => CallSiteInformation?.GetCallerClassName(null, true, true, true);
/// <summary>
/// Gets the callsite member function name
/// </summary>
public string CallerMemberName => CallSiteInformation?.GetCallerMethodName(null, false, true, true);
/// <summary>
/// Gets the callsite source file path
/// </summary>
public string CallerFilePath => CallSiteInformation?.GetCallerFilePath(0);
/// <summary>
/// Gets the callsite source file line number
/// </summary>
public int CallerLineNumber => CallSiteInformation?.GetCallerLineNumber(0) ?? 0;
/// <summary>
/// Gets or sets the exception information.
/// </summary>
[CanBeNull]
public Exception Exception { get; set; }
/// <summary>
/// Gets or sets the logger name.
/// </summary>
[CanBeNull]
public string LoggerName { get; set; }
/// <summary>
/// Gets or sets the log message including any parameter placeholders.
/// </summary>
public string Message
{
get => _message;
set
{
bool rebuildMessageTemplateParameters = ResetMessageTemplateParameters();
_message = value;
ResetFormattedMessage(rebuildMessageTemplateParameters);
}
}
/// <summary>
/// Gets or sets the parameter values or null if no parameters have been specified.
/// </summary>
public object[] Parameters
{
get => _parameters;
set
{
bool rebuildMessageTemplateParameters = ResetMessageTemplateParameters();
_parameters = value;
ResetFormattedMessage(rebuildMessageTemplateParameters);
}
}
/// <summary>
/// Gets or sets the format provider that was provided while logging or <see langword="null" />
/// when no formatProvider was specified.
/// </summary>
public IFormatProvider FormatProvider
{
get => _formatProvider;
set
{
if (!ReferenceEquals(_formatProvider, value))
{
_formatProvider = value;
ResetFormattedMessage(false);
}
}
}
/// <summary>
/// Gets or sets the message formatter for generating <see cref="LogEventInfo.FormattedMessage"/>
/// Uses string.Format(...) when nothing else has been configured.
/// </summary>
public LogMessageFormatter MessageFormatter
{
get => _messageFormatter ?? LogManager.LogFactory.ActiveMessageFormatter;
set
{
var messageFormatter = value ?? LogMessageStringFormatter.Default.MessageFormatter;
if (!ReferenceEquals(_messageFormatter, messageFormatter))
{
_messageFormatter = messageFormatter;
_formattedMessage = null;
ResetFormattedMessage(false);
}
}
}
/// <summary>
/// Gets the formatted message.
/// </summary>
public string FormattedMessage
{
get
{
if (_formattedMessage is null)
{
CalcFormattedMessage();
}
return _formattedMessage;
}
}
/// <summary>
/// Checks if any per-event properties (Without allocation)
/// </summary>
public bool HasProperties
{
get
{
if (_properties != null)
{
return _properties.Count > 0;
}
else
{
return CreateOrUpdatePropertiesInternal(false)?.Count > 0;
}
}
}
/// <summary>
/// Gets the dictionary of per-event context properties.
/// </summary>
public IDictionary<object, object> Properties => CreateOrUpdatePropertiesInternal();
/// <summary>
/// Gets the dictionary of per-event context properties.
/// Internal helper for the PropertiesDictionary type.
/// </summary>
/// <param name="forceCreate">Create the event-properties dictionary, even if no initial template parameters</param>
/// <param name="templateParameters">Provided when having parsed the message template and capture template parameters (else null)</param>
/// <returns></returns>
internal PropertiesDictionary CreateOrUpdatePropertiesInternal(bool forceCreate = true, IList<MessageTemplateParameter> templateParameters = null)
{
var properties = _properties;
if (properties is null)
{
if (forceCreate || templateParameters?.Count > 0 || (templateParameters is null && HasMessageTemplateParameters))
{
properties = new PropertiesDictionary(templateParameters);
Interlocked.CompareExchange(ref _properties, properties, null);
if (templateParameters is null && (!forceCreate || HasMessageTemplateParameters))
{
// Trigger capture of MessageTemplateParameters from logevent-message
CalcFormattedMessage();
}
}
}
else if (templateParameters != null)
{
properties.MessageProperties = templateParameters;
}
return _properties;
}
private bool HasMessageTemplateParameters
{
get
{
// Have not yet parsed/rendered the FormattedMessage, so check with ILogMessageFormatter
if (_formattedMessage is null && _parameters?.Length > 0)
{
var logMessageFormatter = MessageFormatter.Target as ILogMessageFormatter;
return logMessageFormatter?.HasProperties(this) ?? false;
}
return false;
}
}
/// <summary>
/// Gets the named parameters extracted from parsing <see cref="Message"/> as MessageTemplate
/// </summary>
public MessageTemplateParameters MessageTemplateParameters
{
get
{
if (_properties != null && _properties.MessageProperties.Count > 0)
{
return new MessageTemplateParameters(_properties.MessageProperties, _message, _parameters);
}
else if (_parameters?.Length > 0)
{
return new MessageTemplateParameters(_message, _parameters);
}
else
{
return MessageTemplateParameters.Empty; // No parameters, means nothing to parse
}
}
}
/// <summary>
/// Creates the null event.
/// </summary>
/// <returns>Null log event.</returns>
public static LogEventInfo CreateNullEvent()
{
return new LogEventInfo(LogLevel.Off, string.Empty, null, string.Empty, null, null);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param>
/// <param name="message">The message.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message)
{
return new LogEventInfo(logLevel, loggerName, null, message, null, null);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
[MessageTemplateFormatMethod("message")]
public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object[] parameters)
{
return new LogEventInfo(logLevel, loggerName, formatProvider, message, parameters, null);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, object message)
{
Exception exception = message as Exception;
if (exception is null && message is LogEventInfo logEvent)
{
logEvent.LoggerName = loggerName;
logEvent.Level = logLevel;
logEvent.FormatProvider = formatProvider ?? logEvent.FormatProvider;
return logEvent;
}
formatProvider = formatProvider ?? (exception != null ? ExceptionMessageFormatProvider.Instance : null);
return new LogEventInfo(logLevel, loggerName, formatProvider, "{0}", new[] { message }, exception);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param>
/// <param name="exception">The exception.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message)
{
return new LogEventInfo(logLevel, loggerName, formatProvider, message, null, exception);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param>
/// <param name="exception">The exception.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
[MessageTemplateFormatMethod("message")]
public static LogEventInfo Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object[] parameters)
{
return new LogEventInfo(logLevel, loggerName, formatProvider, message, parameters, exception);
}
/// <summary>
/// Creates <see cref="AsyncLogEventInfo"/> from this <see cref="LogEventInfo"/> by attaching the specified asynchronous continuation.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <returns>Instance of <see cref="AsyncLogEventInfo"/> with attached continuation.</returns>
public AsyncLogEventInfo WithContinuation(AsyncContinuation asyncContinuation)
{
return new AsyncLogEventInfo(this, asyncContinuation);
}
/// <summary>
/// Returns a string representation of this log event.
/// </summary>
/// <returns>String representation of the log event.</returns>
public override string ToString()
{
return $"Log Event: Logger='{LoggerName}' Level={Level} Message='{FormattedMessage}'";
}
/// <summary>
/// Sets the stack trace for the event info.
/// </summary>
/// <param name="stackTrace">The stack trace.</param>
/// <param name="userStackFrame">Index of the first user stack frame within the stack trace (Negative means NLog should skip stackframes from System-assemblies).</param>
public void SetStackTrace(StackTrace stackTrace, int userStackFrame)
{
GetCallSiteInformationInternal().SetStackTrace(stackTrace, userStackFrame >= 0 ? userStackFrame : (int?)null);
}
/// <summary>
/// Sets the details retrieved from the Caller Information Attributes
/// </summary>
/// <param name="callerClassName"></param>
/// <param name="callerMemberName"></param>
/// <param name="callerFilePath"></param>
/// <param name="callerLineNumber"></param>
public void SetCallerInfo(string callerClassName, string callerMemberName, string callerFilePath, int callerLineNumber)
{
GetCallSiteInformationInternal().SetCallerInfo(callerClassName, callerMemberName, callerFilePath, callerLineNumber);
}
internal void AddCachedLayoutValue(Layout layout, object value)
{
if (_layoutCache is null)
{
var dictionary = new Dictionary<Layout, object>();
dictionary[layout] = value; // Faster than collection initializer
if (Interlocked.CompareExchange(ref _layoutCache, dictionary, null) is null)
{
return; // No need to use lock
}
}
lock (_layoutCache)
{
_layoutCache[layout] = value;
}
}
internal bool TryGetCachedLayoutValue(Layout layout, out object value)
{
if (_layoutCache is null)
{
// We don't need lock to see if dictionary has been created
value = null;
return false;
}
lock (_layoutCache)
{
// dictionary is always non-empty when created
return _layoutCache.TryGetValue(layout, out value);
}
}
private static bool NeedToPreformatMessage(object[] parameters)
{
// we need to preformat message if it contains any parameters which could possibly
// do logging in their ToString()
if (parameters is null || parameters.Length == 0)
{
return false;
}
if (parameters.Length > 5)
{
// too many parameters, too costly to check
return true;
}
for (int i = 0; i < parameters.Length; ++i)
{
if (!IsSafeToDeferFormatting(parameters[i]))
return true;
}
return false;
}
private static bool IsSafeToDeferFormatting(object value)
{
return Convert.GetTypeCode(value) != TypeCode.Object;
}
internal bool IsLogEventThreadAgnosticImmutable()
{
if (Exception != null)
return false;
if (_formattedMessage != null && _parameters?.Length > 0)
return false;
var properties = CreateOrUpdatePropertiesInternal(false);
if (properties is null || properties.Count == 0)
return true; // No mutable state, no need to precalculate
if (properties.Count > 5)
return false; // too many properties, too costly to check
if (properties.Count == _parameters?.Length && properties.Count == properties.MessageProperties.Count)
return true; // Already checked formatted message, no need to do it twice
return HasImmutableProperties(properties);
}
private static bool HasImmutableProperties(PropertiesDictionary properties)
{
if (properties.Count == properties.MessageProperties.Count)
{
// Skip enumerator allocation when all properties comes from the message-template
for (int i = 0; i < properties.MessageProperties.Count; ++i)
{
var property = properties.MessageProperties[i];
if (!IsSafeToDeferFormatting(property.Value))
return false;
}
}
else
{
// Already spent the time on allocating a Dictionary, also have time for an enumerator
foreach (var property in properties)
{
if (!IsSafeToDeferFormatting(property.Value))
return false;
}
}
return true;
}
internal void SetMessageFormatter([NotNull] LogMessageFormatter messageFormatter, [CanBeNull] LogMessageFormatter singleTargetMessageFormatter)
{
bool hasCustomMessageFormatter = _messageFormatter != null;
if (!hasCustomMessageFormatter)
{
_messageFormatter = messageFormatter;
}
if (hasCustomMessageFormatter || NeedToPreformatMessage(_parameters))
{
CalcFormattedMessage();
}
else
{
if (singleTargetMessageFormatter != null && _parameters?.Length > 0 && _message?.Length < 256)
{
// Change MessageFormatter so it writes directly to StringBuilder without string-allocation
_messageFormatter = singleTargetMessageFormatter;
}
}
}
private void CalcFormattedMessage()
{
try
{
_formattedMessage = MessageFormatter(this);
}
catch (Exception exception)
{
_formattedMessage = Message ?? string.Empty;
InternalLogger.Warn(exception, "Error when formatting a message.");
if (exception.MustBeRethrown())
{
throw;
}
}
}
internal void AppendFormattedMessage(ILogMessageFormatter messageFormatter, System.Text.StringBuilder builder)
{
if (_formattedMessage != null)
{
builder.Append(_formattedMessage);
}
else if (_parameters?.Length > 0 && !string.IsNullOrEmpty(_message))
{
int originalLength = builder.Length;
try
{
messageFormatter.AppendFormattedMessage(this, builder);
}
catch (Exception ex)
{
builder.Length = originalLength;
builder.Append(_message);
InternalLogger.Warn(ex, "Error when formatting a message.");
if (ex.MustBeRethrown())
{
throw;
}
}
}
else
{
builder.Append(FormattedMessage);
}
}
private void ResetFormattedMessage(bool rebuildMessageTemplateParameters)
{
if (_messageFormatter is null || _messageFormatter.Target is ILogMessageFormatter)
{
_formattedMessage = null;
}
if (rebuildMessageTemplateParameters && HasMessageTemplateParameters)
{
CalcFormattedMessage();
}
}
private bool ResetMessageTemplateParameters()
{
if (_properties != null)
{
if (HasMessageTemplateParameters)
_properties.MessageProperties = null;
return _properties.MessageProperties.Count == 0;
}
return false;
}
}
}