-
Notifications
You must be signed in to change notification settings - Fork 765
/
LogRecord.cs
597 lines (530 loc) · 18.6 KB
/
LogRecord.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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
using System.Diagnostics;
#if EXPOSE_EXPERIMENTAL_FEATURES && NET
using System.Diagnostics.CodeAnalysis;
#endif
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Logging;
using OpenTelemetry.Internal;
namespace OpenTelemetry.Logs;
/// <summary>
/// Stores details about a log message.
/// </summary>
public sealed class LogRecord
{
internal LogRecordData Data;
internal LogRecordILoggerData ILoggerData;
internal IReadOnlyList<KeyValuePair<string, object?>>? AttributeData;
internal List<KeyValuePair<string, object?>>? AttributeStorage;
internal List<object?>? ScopeStorage;
internal LogRecordSource Source = LogRecordSource.CreatedManually;
internal int PoolReferenceCount = int.MaxValue;
private static readonly Action<object?, List<object?>> AddScopeToBufferedList = (object? scope, List<object?> state) =>
{
state.Add(scope);
};
internal LogRecord()
{
}
// Note: Some users are calling this with reflection. Try not to change the signature to be nice.
[Obsolete("Call LogRecordPool.Rent instead.")]
internal LogRecord(
IExternalScopeProvider? scopeProvider,
DateTime timestamp,
string categoryName,
LogLevel logLevel,
EventId eventId,
string? formattedMessage,
object? state,
Exception? exception,
IReadOnlyList<KeyValuePair<string, object?>>? stateValues)
{
var activity = Activity.Current;
this.Data = new(activity)
{
TimestampBacking = timestamp,
Body = formattedMessage,
};
OpenTelemetryLogger.SetLogRecordSeverityFields(ref this.Data, logLevel);
this.ILoggerData = new()
{
TraceState = activity?.TraceStateString,
FormattedMessage = formattedMessage,
EventId = eventId,
Exception = exception,
State = state,
ScopeProvider = scopeProvider,
};
if (stateValues != null && stateValues.Count > 0)
{
var lastAttribute = stateValues[stateValues.Count - 1];
if (lastAttribute.Key == "{OriginalFormat}"
&& lastAttribute.Value is string template)
{
this.Data.Body = template;
}
this.AttributeData = stateValues;
}
this.Logger = InstrumentationScopeLogger.GetInstrumentationScopeLoggerForName(categoryName);
}
internal enum LogRecordSource
{
/// <summary>
/// A <see cref="LogRecord"/> created manually.
/// </summary>
CreatedManually,
/// <summary>
/// A <see cref="LogRecord"/> rented from the <see cref="LogRecordThreadStaticPool"/>.
/// </summary>
FromThreadStaticPool,
/// <summary>
/// A <see cref="LogRecord"/> rented from the <see cref="LogRecordSharedPool"/>.
/// </summary>
FromSharedPool,
}
/// <summary>
/// Gets or sets the log timestamp.
/// </summary>
/// <remarks>
/// Note: If <see cref="Timestamp"/> is set to a value with <see
/// cref="DateTimeKind.Local"/> it will be automatically converted to
/// UTC using <see cref="DateTime.ToUniversalTime"/>.
/// </remarks>
public DateTime Timestamp
{
get => this.Data.Timestamp;
set => this.Data.Timestamp = value;
}
/// <summary>
/// Gets or sets the log <see cref="ActivityTraceId"/>.
/// </summary>
public ActivityTraceId TraceId
{
get => this.Data.TraceId;
set => this.Data.TraceId = value;
}
/// <summary>
/// Gets or sets the log <see cref="ActivitySpanId"/>.
/// </summary>
public ActivitySpanId SpanId
{
get => this.Data.SpanId;
set => this.Data.SpanId = value;
}
/// <summary>
/// Gets or sets the log <see cref="ActivityTraceFlags"/>.
/// </summary>
public ActivityTraceFlags TraceFlags
{
get => this.Data.TraceFlags;
set => this.Data.TraceFlags = value;
}
/// <summary>
/// Gets or sets the log trace state.
/// </summary>
/// <remarks>
/// Note: Only set if <see
/// cref="OpenTelemetryLoggerOptions.IncludeTraceState"/> is enabled.
/// </remarks>
public string? TraceState
{
get => this.ILoggerData.TraceState;
set => this.ILoggerData.TraceState = value;
}
#if EXPOSE_EXPERIMENTAL_FEATURES
/// <summary>
/// Gets or sets the log category name.
/// </summary>
/// <remarks>
/// Note: <see cref="CategoryName"/> is an alias for the <see
/// cref="Logger.Name"/> accessed via the <see cref="Logger"/> property.
/// Setting a new value for <see cref="CategoryName"/> will result in a new
/// <see cref="Logger"/> being set.
/// </remarks>
#else
/// <summary>
/// Gets or sets the log category name.
/// </summary>
#endif
public string? CategoryName
{
get => this.Logger.Name;
set
{
if (this.Logger.Name != value)
{
this.Logger = InstrumentationScopeLogger.GetInstrumentationScopeLoggerForName(value);
}
}
}
/// <summary>
/// Gets or sets the log <see cref="Microsoft.Extensions.Logging.LogLevel"/>.
/// </summary>
#if EXPOSE_EXPERIMENTAL_FEATURES
[Obsolete("Use Severity instead. LogLevel will be removed in a future version.")]
#endif
public LogLevel LogLevel
{
get
{
if (this.Data.Severity.HasValue)
{
uint severity = (uint)this.Data.Severity.Value;
if (severity >= 1 && severity <= 24)
{
return (LogLevel)((severity - 1) / 4);
}
}
return LogLevel.Trace;
}
set
{
OpenTelemetryLogger.SetLogRecordSeverityFields(ref this.Data, value);
}
}
/// <summary>
/// Gets or sets the log <see cref="Microsoft.Extensions.Logging.EventId"/>.
/// </summary>
/// <remarks>
/// Note: <see cref="EventId"/> is only set when emitting logs through <see cref="ILogger"/>.
/// </remarks>
public EventId EventId
{
get => this.ILoggerData.EventId;
set => this.ILoggerData.EventId = value;
}
/// <summary>
/// Gets or sets the log formatted message.
/// </summary>
/// <remarks>
/// Notes:
/// <list type="bullet">
/// <item><see cref="FormattedMessage"/> is only set when emitting logs
/// through <see cref="ILogger"/>.</item>
/// <item>Set if <see
/// cref="OpenTelemetryLoggerOptions.IncludeFormattedMessage"/> is enabled
/// or <c>{OriginalFormat}</c> attribute (message template) is not
/// found.</item>
/// </list>
/// </remarks>
public string? FormattedMessage
{
get => this.ILoggerData.FormattedMessage;
set => this.ILoggerData.FormattedMessage = value;
}
/// <summary>
/// Gets or sets the log body.
/// </summary>
/// <remarks>
/// Note: Set to the <c>{OriginalFormat}</c> attribute (message
/// template) if found otherwise the formatted log message.
/// </remarks>
public string? Body
{
get => this.Data.Body;
set => this.Data.Body = value;
}
/// <summary>
/// Gets or sets the raw state attached to the log.
/// </summary>
/// <remarks>
/// Notes:
/// <list type="bullet">
/// <item><see cref="State"/> is only set when emitting logs
/// through <see cref="ILogger"/>.</item>
/// <item>Set to <see langword="null"/> when <see
/// cref="OpenTelemetryLoggerOptions.ParseStateValues"/> is enabled.</item>
/// <item><see cref="Attributes"/> are automatically updated if <see
/// cref="State"/> is set directly.</item>
/// </list>
/// </remarks>
[Obsolete("State cannot be accessed safely outside of an ILogger.Log call stack. Use Attributes instead to safely access the data attached to a LogRecord. State will be removed in a future version.")]
public object? State
{
get => this.ILoggerData.State;
set
{
if (ReferenceEquals(this.ILoggerData.State, value))
{
return;
}
if (this.AttributeData is not null)
{
this.AttributeData = OpenTelemetryLogger.ProcessState(this, ref this.ILoggerData, value, includeAttributes: true, parseStateValues: false);
}
else
{
this.ILoggerData.State = value;
}
}
}
/// <summary>
/// Gets or sets the state values attached to the log.
/// </summary>
/// <remarks><inheritdoc cref="Attributes" /></remarks>
[Obsolete("Use Attributes instead. StateValues will be removed in a future version.")]
public IReadOnlyList<KeyValuePair<string, object?>>? StateValues
{
get => this.Attributes;
set => this.Attributes = value;
}
/// <summary>
/// Gets or sets the attributes attached to the log.
/// </summary>
/// <remarks>
/// Notes:
/// <list type="bullet">
/// <item>Set when <see
/// cref="OpenTelemetryLoggerOptions.IncludeAttributes"/> is enabled and log
/// record state implements <see cref="IReadOnlyList{T}"/> or <see
/// cref="IEnumerable{T}"/> of <see cref="KeyValuePair{TKey, TValue}"/>s
/// (where TKey is <c>string</c> and TValue is <c>object</c>) or <see
/// cref="OpenTelemetryLoggerOptions.ParseStateValues"/> is enabled
/// otherwise <see langword="null"/>.</item>
/// <item><see cref="State"/> is automatically updated if <see
/// cref="Attributes"/> are set directly.</item>
/// </list>
/// </remarks>
public IReadOnlyList<KeyValuePair<string, object?>>? Attributes
{
get => this.AttributeData;
set
{
if (ReferenceEquals(this.AttributeData, value))
{
return;
}
if (this.ILoggerData.State is not null)
{
this.ILoggerData.State = value;
}
this.AttributeData = value;
}
}
/// <summary>
/// Gets or sets the log <see cref="System.Exception"/>.
/// </summary>
/// <remarks>
/// Note: <see cref="Exception"/> is only set when emitting logs through <see cref="ILogger"/>.
/// </remarks>
public Exception? Exception
{
get => this.ILoggerData.Exception;
set => this.ILoggerData.Exception = value;
}
#if EXPOSE_EXPERIMENTAL_FEATURES
/// <summary>
/// Gets or sets the original string representation of the severity as it is
/// known at the source.
/// </summary>
/// <remarks><inheritdoc cref="Sdk.CreateLoggerProviderBuilder" path="/remarks"/></remarks>
#if NET
[Experimental(DiagnosticDefinitions.LogsBridgeExperimentalApi, UrlFormat = DiagnosticDefinitions.ExperimentalApiUrlFormat)]
#endif
public
#else
/// <summary>
/// Gets or sets the original string representation of the severity as it is
/// known at the source.
/// </summary>
internal
#endif
string? SeverityText
{
get => this.Data.SeverityText;
set => this.Data.SeverityText = value;
}
#if EXPOSE_EXPERIMENTAL_FEATURES
/// <summary>
/// Gets or sets the log <see cref="LogRecordSeverity"/>.
/// </summary>
/// <remarks><inheritdoc cref="Sdk.CreateLoggerProviderBuilder" path="/remarks"/></remarks>
#if NET
[Experimental(DiagnosticDefinitions.LogsBridgeExperimentalApi, UrlFormat = DiagnosticDefinitions.ExperimentalApiUrlFormat)]
#endif
public
#else
/// <summary>
/// Gets or sets the log <see cref="LogRecordSeverity"/>.
/// </summary>
internal
#endif
LogRecordSeverity? Severity
{
get => this.Data.Severity;
set => this.Data.Severity = value;
}
#if EXPOSE_EXPERIMENTAL_FEATURES
/// <summary>
/// Gets the <see cref="Logs.Logger"/> associated with the <see
/// cref="LogRecord"/>.
/// </summary>
/// <remarks>
/// <para><inheritdoc cref="Sdk.CreateLoggerProviderBuilder" path="/remarks"/></para>
/// Note: When using the Log Bridge API (for example <see
/// cref="Logger.EmitLog(in LogRecordData)"/>) <see cref="Logger"/> is
/// typically the <see cref="Logs.Logger"/> which emitted the <see
/// cref="LogRecord"/> however the value may be different if <see
/// cref="CategoryName"/> is modified.</remarks>
#if NET
[Experimental(DiagnosticDefinitions.LogsBridgeExperimentalApi, UrlFormat = DiagnosticDefinitions.ExperimentalApiUrlFormat)]
#endif
public Logger Logger { get; internal set; } = InstrumentationScopeLogger.Default;
#else
/// <summary>
/// Gets or sets the <see cref="Logs.Logger"/> associated with the <see
/// cref="LogRecord"/>.
/// </summary>
internal Logger Logger { get; set; } = InstrumentationScopeLogger.Default;
#endif
/// <summary>
/// Executes callback for each currently active scope objects in order
/// of creation. All callbacks are guaranteed to be called inline from
/// this method.
/// </summary>
/// <typeparam name="TState">State.</typeparam>
/// <param name="callback">The callback to be executed for every scope object.</param>
/// <param name="state">The state object to be passed into the callback.</param>
public void ForEachScope<TState>(Action<LogRecordScope, TState> callback, TState state)
{
Guard.ThrowIfNull(callback);
var forEachScopeState = new ScopeForEachState<TState>(callback, state);
var bufferedScopes = this.ILoggerData.BufferedScopes;
if (bufferedScopes != null)
{
foreach (object? scope in bufferedScopes)
{
ScopeForEachState<TState>.ForEachScope(scope, forEachScopeState);
}
}
else
{
this.ILoggerData.ScopeProvider?.ForEachScope(ScopeForEachState<TState>.ForEachScope, forEachScopeState);
}
}
/// <summary>
/// Gets a reference to the <see cref="LogRecordData"/> for the log message.
/// </summary>
/// <returns><see cref="LogRecordData"/>.</returns>
internal ref LogRecordData GetDataRef()
{
return ref this.Data;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void ResetReferenceCount()
{
this.PoolReferenceCount = 1;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void AddReference()
{
Interlocked.Increment(ref this.PoolReferenceCount);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal int RemoveReference()
{
return Interlocked.Decrement(ref this.PoolReferenceCount);
}
// Note: Typically called when LogRecords are added into a batch so they
// can be safely processed outside of the log call chain.
internal void Buffer()
{
// Note: Attributes are buffered because some states are not safe to
// access outside of the log call chain. See:
// https://github.com/open-telemetry/opentelemetry-dotnet/issues/2905
this.BufferLogAttributes();
this.BufferLogScopes();
}
internal LogRecord Copy()
{
// Note: We only buffer scopes here because attributes are copied
// directly below.
this.BufferLogScopes();
return new()
{
Data = this.Data,
ILoggerData = this.ILoggerData.Copy(),
AttributeData = this.AttributeData is null ? null : new List<KeyValuePair<string, object?>>(this.AttributeData),
Logger = this.Logger,
};
}
/// <summary>
/// Buffers the attributes attached to the log into a list so that they
/// can be safely processed after the log message lifecycle has ended.
/// </summary>
private void BufferLogAttributes()
{
var attributes = this.AttributeData;
if (attributes == null || attributes == this.AttributeStorage)
{
return;
}
var attributeStorage = this.AttributeStorage ??= new List<KeyValuePair<string, object?>>(attributes.Count);
// Note: AddRange here will copy all of the KeyValuePairs from
// attributes to AttributeStorage. This "captures" the state and
// fixes issues where the values are generated at enumeration time
// like
// https://github.com/open-telemetry/opentelemetry-dotnet/issues/2905.
attributeStorage.AddRange(attributes);
this.AttributeData = attributeStorage;
}
/// <summary>
/// Buffers the scopes attached to the log into a list so that they can
/// be safely processed after the log message lifecycle has ended.
/// </summary>
private void BufferLogScopes()
{
var scopeProvider = this.ILoggerData.ScopeProvider;
if (scopeProvider == null)
{
return;
}
var scopeStorage = this.ScopeStorage ??= new List<object?>(LogRecordPoolHelper.DefaultMaxNumberOfScopes);
scopeProvider.ForEachScope(AddScopeToBufferedList, scopeStorage);
this.ILoggerData.ScopeProvider = null;
this.ILoggerData.BufferedScopes = scopeStorage;
}
internal struct LogRecordILoggerData
{
public string? TraceState;
public EventId EventId;
public string? FormattedMessage;
public Exception? Exception;
public object? State;
public IExternalScopeProvider? ScopeProvider;
public List<object?>? BufferedScopes;
public LogRecordILoggerData Copy()
{
var copy = new LogRecordILoggerData
{
TraceState = this.TraceState,
EventId = this.EventId,
FormattedMessage = this.FormattedMessage,
Exception = this.Exception,
State = this.State,
};
var bufferedScopes = this.BufferedScopes;
if (bufferedScopes != null)
{
copy.BufferedScopes = new List<object?>(bufferedScopes);
}
return copy;
}
}
private readonly struct ScopeForEachState<TState>
{
public static readonly Action<object?, ScopeForEachState<TState>> ForEachScope = (object? scope, ScopeForEachState<TState> state) =>
{
LogRecordScope logRecordScope = new LogRecordScope(scope);
state.Callback(logRecordScope, state.UserState);
};
public readonly Action<LogRecordScope, TState> Callback;
public readonly TState UserState;
public ScopeForEachState(Action<LogRecordScope, TState> callback, TState state)
{
this.Callback = callback;
this.UserState = state;
}
}
}