-
Notifications
You must be signed in to change notification settings - Fork 888
Expand file tree
/
Copy pathOpenTelemetryLogger.cs
More file actions
241 lines (198 loc) · 8.16 KB
/
OpenTelemetryLogger.cs
File metadata and controls
241 lines (198 loc) · 8.16 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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Logging;
using OpenTelemetry.Internal;
namespace OpenTelemetry.Logs;
internal sealed class OpenTelemetryLogger : ILogger
{
private static readonly string[] LogLevels =
[
nameof(LogLevel.Trace),
nameof(LogLevel.Debug),
nameof(LogLevel.Information),
nameof(LogLevel.Warning),
nameof(LogLevel.Error),
nameof(LogLevel.Critical),
nameof(LogLevel.None),
];
private readonly LoggerProviderSdk provider;
private readonly OpenTelemetryLoggerOptions options;
private readonly InstrumentationScopeLogger instrumentationScope;
internal OpenTelemetryLogger(
LoggerProviderSdk provider,
OpenTelemetryLoggerOptions options,
string categoryName)
{
Debug.Assert(categoryName != null, "categoryName was null");
this.provider = provider;
this.options = options;
this.instrumentationScope = InstrumentationScopeLogger.GetInstrumentationScopeLoggerForName(categoryName);
}
internal IExternalScopeProvider? ScopeProvider { get; set; }
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
if (!this.IsEnabled(logLevel))
{
return;
}
var provider = this.provider;
var processor = this.provider.Processor;
if (processor != null)
{
var activity = Activity.Current;
var pool = this.provider.LogRecordPool;
var record = pool.Rent();
ref var iloggerData = ref record.ILoggerData;
iloggerData.TraceState = this.options.IncludeTraceState && activity != null
? activity.TraceStateString
: null;
iloggerData.EventId = eventId;
iloggerData.Exception = exception;
iloggerData.ScopeProvider = this.options.IncludeScopes ? this.ScopeProvider : null;
iloggerData.BufferedScopes = null;
ref var data = ref record.Data;
data.TimestampBacking = DateTime.UtcNow;
data.ObservedTimestampBacking = data.TimestampBacking;
SetLogRecordSeverityFields(ref data, logLevel);
LogRecordData.SetActivityContext(ref data, activity);
var attributes = record.AttributeData =
ProcessState(record, ref iloggerData, in state, this.options.IncludeAttributes, this.options.ParseStateValues);
if (!TryGetOriginalFormatFromAttributes(attributes, out var originalFormat))
{
var formattedMessage = formatter?.Invoke(state, exception) ?? state?.ToString();
data.Body = formattedMessage;
iloggerData.FormattedMessage = formattedMessage;
}
else
{
data.Body = originalFormat;
iloggerData.FormattedMessage = this.options.IncludeFormattedMessage
? formatter?.Invoke(state, exception) ?? state?.ToString()
: null;
}
record.Logger = this.instrumentationScope;
processor.OnEnd(record);
iloggerData.ScopeProvider = null;
// Attempt to return the LogRecord to the pool. This will no-op
// if a batch exporter has added a reference.
pool.Return(record);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsEnabled(LogLevel logLevel)
=> logLevel != LogLevel.None && !Sdk.SuppressInstrumentation;
public IDisposable BeginScope<TState>(TState state)
where TState : notnull => this.ScopeProvider?.Push(state) ?? NullScope.Instance;
internal static void SetLogRecordSeverityFields(ref LogRecordData logRecordData, LogLevel logLevel)
{
var intLogLevel = (uint)logLevel;
if (intLogLevel < 6)
{
logRecordData.Severity = (LogRecordSeverity)((intLogLevel * 4) + 1);
logRecordData.SeverityText = LogLevels[intLogLevel];
}
else
{
logRecordData.Severity = null;
logRecordData.SeverityText = null;
}
}
internal static IReadOnlyList<KeyValuePair<string, object?>>? ProcessState<TState>(
LogRecord logRecord,
ref LogRecord.LogRecordILoggerData iLoggerData,
in TState state,
bool includeAttributes,
bool parseStateValues)
{
if (!includeAttributes
|| (!typeof(TState).IsValueType && state is null))
{
iLoggerData.State = null;
return null;
}
if (typeof(TState) == typeof(LogRecordAttributeList))
{
// Note: This block is written to be elided by the JIT when
// TState is not LogRecordAttributeList or optimized when it is.
// For users that pass LogRecordAttributeList as TState to
// ILogger.Log this will avoid boxing the struct.
var logRecordAttributes = (LogRecordAttributeList)(object)state!;
var exportedAttributes = logRecordAttributes.Export(ref logRecord.AttributeStorage);
// Note: This is to preserve legacy behavior where State is exposed
// if we didn't parse state. We use exportedAttributes here to prevent a
// boxing of struct LogRecordAttributeList.
iLoggerData.State = !parseStateValues ? exportedAttributes : null;
return exportedAttributes;
}
else if (state is IReadOnlyList<KeyValuePair<string, object?>> stateList)
{
// Note: This is to preserve legacy behavior where State is exposed
// if we didn't parse state. We use stateList here to prevent a
// second boxing of struct TStates.
iLoggerData.State = !parseStateValues ? stateList : null;
return stateList;
}
else if (state is IEnumerable<KeyValuePair<string, object?>> stateValues)
{
// Note: This is to preserve legacy behavior where State is exposed
// if we didn't parse state. We use stateValues here to prevent a
// second boxing of struct TStates.
iLoggerData.State = !parseStateValues ? stateValues : null;
var attributeStorage = logRecord.AttributeStorage;
if (attributeStorage == null)
{
return logRecord.AttributeStorage = [.. stateValues];
}
else
{
attributeStorage.AddRange(stateValues);
return attributeStorage;
}
}
else if (!parseStateValues)
{
// Note: This is to preserve legacy behavior where State is
// exposed if we didn't parse state.
iLoggerData.State = state;
return null;
}
else
{
// Note: We clear State because the LogRecord we are processing may
// have come from the pool and may have State from a prior log.
iLoggerData.State = null;
OpenTelemetrySdkEventSource.Log.LoggerProcessStateSkipped<TState>();
return [];
}
}
private static bool TryGetOriginalFormatFromAttributes(
IReadOnlyList<KeyValuePair<string, object?>>? attributes,
[NotNullWhen(true)] out string? originalFormat)
{
if (attributes != null && attributes.Count > 0)
{
for (var i = attributes.Count - 1; i >= 0; i--)
{
var attribute = attributes[i];
if (attribute.Key == "{OriginalFormat}"
&& attribute.Value is string tempOriginalFormat)
{
originalFormat = tempOriginalFormat;
return true;
}
}
}
originalFormat = null;
return false;
}
private sealed class NullScope : IDisposable
{
public static NullScope Instance { get; } = new();
public void Dispose()
{
}
}
}