-
Notifications
You must be signed in to change notification settings - Fork 751
/
OtlpLogRecordTransformer.cs
281 lines (242 loc) · 11.1 KB
/
OtlpLogRecordTransformer.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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using Google.Protobuf;
using OpenTelemetry.Internal;
using OpenTelemetry.Logs;
using OpenTelemetry.Trace;
using OtlpCollector = OpenTelemetry.Proto.Collector.Logs.V1;
using OtlpCommon = OpenTelemetry.Proto.Common.V1;
using OtlpLogs = OpenTelemetry.Proto.Logs.V1;
using OtlpResource = OpenTelemetry.Proto.Resource.V1;
namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation;
internal sealed class OtlpLogRecordTransformer
{
internal static readonly ConcurrentBag<OtlpLogs.ScopeLogs> LogListPool = new();
private readonly SdkLimitOptions sdkLimitOptions;
private readonly ExperimentalOptions experimentalOptions;
public OtlpLogRecordTransformer(SdkLimitOptions sdkLimitOptions, ExperimentalOptions experimentalOptions)
{
this.sdkLimitOptions = sdkLimitOptions;
this.experimentalOptions = experimentalOptions;
}
internal OtlpCollector.ExportLogsServiceRequest BuildExportRequest(
OtlpResource.Resource processResource,
in Batch<LogRecord> logRecordBatch)
{
// TODO: https://github.com/open-telemetry/opentelemetry-dotnet/issues/4943
Dictionary<string, OtlpLogs.ScopeLogs> logsByCategory = new Dictionary<string, OtlpLogs.ScopeLogs>();
var request = new OtlpCollector.ExportLogsServiceRequest();
var resourceLogs = new OtlpLogs.ResourceLogs
{
Resource = processResource,
};
request.ResourceLogs.Add(resourceLogs);
foreach (var logRecord in logRecordBatch)
{
var otlpLogRecord = this.ToOtlpLog(logRecord);
if (otlpLogRecord != null)
{
var scopeName = logRecord.Logger.Name;
if (!logsByCategory.TryGetValue(scopeName, out var scopeLogs))
{
scopeLogs = this.GetLogListFromPool(scopeName);
logsByCategory.Add(scopeName, scopeLogs);
resourceLogs.ScopeLogs.Add(scopeLogs);
}
scopeLogs.LogRecords.Add(otlpLogRecord);
}
}
return request;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void Return(OtlpCollector.ExportLogsServiceRequest request)
{
var resourceLogs = request.ResourceLogs.FirstOrDefault();
if (resourceLogs == null)
{
return;
}
foreach (var scope in resourceLogs.ScopeLogs)
{
scope.LogRecords.Clear();
LogListPool.Add(scope);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal OtlpLogs.ScopeLogs GetLogListFromPool(string name)
{
if (!LogListPool.TryTake(out var logs))
{
logs = new OtlpLogs.ScopeLogs
{
Scope = new OtlpCommon.InstrumentationScope
{
Name = name, // Name is enforced to not be null, but it can be empty.
Version = string.Empty, // proto requires this to be non-null.
},
};
}
else
{
logs.Scope.Name = name;
logs.Scope.Version = string.Empty;
}
return logs;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal OtlpLogs.LogRecord? ToOtlpLog(LogRecord logRecord)
{
OtlpLogs.LogRecord? otlpLogRecord = null;
try
{
var timestamp = (ulong)logRecord.Timestamp.ToUnixTimeNanoseconds();
otlpLogRecord = new OtlpLogs.LogRecord
{
TimeUnixNano = timestamp,
ObservedTimeUnixNano = timestamp,
SeverityNumber = GetSeverityNumber(logRecord.Severity),
};
if (!string.IsNullOrWhiteSpace(logRecord.SeverityText))
{
otlpLogRecord.SeverityText = logRecord.SeverityText;
}
else if (logRecord.Severity.HasValue)
{
otlpLogRecord.SeverityText = logRecord.Severity.Value.ToShortName();
}
var attributeValueLengthLimit = this.sdkLimitOptions.LogRecordAttributeValueLengthLimit;
var attributeCountLimit = this.sdkLimitOptions.LogRecordAttributeCountLimit ?? int.MaxValue;
if (this.experimentalOptions.EmitLogEventAttributes)
{
if (logRecord.EventId.Id != default)
{
AddIntAttribute(otlpLogRecord, ExperimentalOptions.LogRecordEventIdAttribute, logRecord.EventId.Id, attributeCountLimit);
}
if (!string.IsNullOrEmpty(logRecord.EventId.Name))
{
AddStringAttribute(otlpLogRecord, ExperimentalOptions.LogRecordEventNameAttribute, logRecord.EventId.Name, attributeCountLimit, attributeValueLengthLimit);
}
}
if (logRecord.Exception != null)
{
AddStringAttribute(otlpLogRecord, SemanticConventions.AttributeExceptionType, logRecord.Exception.GetType().Name, attributeCountLimit, attributeValueLengthLimit);
AddStringAttribute(otlpLogRecord, SemanticConventions.AttributeExceptionMessage, logRecord.Exception.Message, attributeCountLimit, attributeValueLengthLimit);
AddStringAttribute(otlpLogRecord, SemanticConventions.AttributeExceptionStacktrace, logRecord.Exception.ToInvariantString(), attributeCountLimit, attributeValueLengthLimit);
}
bool bodyPopulatedFromFormattedMessage = false;
if (logRecord.FormattedMessage != null)
{
otlpLogRecord.Body = new OtlpCommon.AnyValue { StringValue = logRecord.FormattedMessage };
bodyPopulatedFromFormattedMessage = true;
}
if (logRecord.Attributes != null)
{
foreach (var attribute in logRecord.Attributes)
{
// Special casing {OriginalFormat}
// See https://github.com/open-telemetry/opentelemetry-dotnet/pull/3182
// for explanation.
if (attribute.Key.Equals("{OriginalFormat}") && !bodyPopulatedFromFormattedMessage)
{
otlpLogRecord.Body = new OtlpCommon.AnyValue { StringValue = attribute.Value as string };
}
else
{
AddAttribute(otlpLogRecord, attribute, attributeCountLimit, attributeValueLengthLimit);
}
}
// Supports setting Body directly on LogRecord for the Logs Bridge API.
if (otlpLogRecord.Body == null && logRecord.Body != null)
{
// If {OriginalFormat} is not present in the attributes,
// use logRecord.Body if it is set.
otlpLogRecord.Body = new OtlpCommon.AnyValue { StringValue = logRecord.Body };
}
}
if (logRecord.TraceId != default && logRecord.SpanId != default)
{
byte[] traceIdBytes = new byte[16];
byte[] spanIdBytes = new byte[8];
logRecord.TraceId.CopyTo(traceIdBytes);
logRecord.SpanId.CopyTo(spanIdBytes);
otlpLogRecord.TraceId = UnsafeByteOperations.UnsafeWrap(traceIdBytes);
otlpLogRecord.SpanId = UnsafeByteOperations.UnsafeWrap(spanIdBytes);
otlpLogRecord.Flags = (uint)logRecord.TraceFlags;
}
logRecord.ForEachScope(ProcessScope, otlpLogRecord);
void ProcessScope(LogRecordScope scope, OtlpLogs.LogRecord otlpLog)
{
foreach (var scopeItem in scope)
{
if (scopeItem.Key.Equals("{OriginalFormat}") || string.IsNullOrEmpty(scopeItem.Key))
{
// Ignore if the scope key is empty.
// Ignore if the scope key is {OriginalFormat}
// Attributes should not contain duplicates,
// and it is expensive to de-dup, so this
// exporter is going to pass the scope items as is.
// {OriginalFormat} is going to be the key
// if one uses formatted string for scopes
// and if there are nested scopes, this is
// guaranteed to create duplicate keys.
// Similar for empty keys, which is what the
// key is going to be if user simply
// passes a string as scope.
// To summarize this exporter only allows
// IReadOnlyList<KeyValuePair<string, object?>>
// or IEnumerable<KeyValuePair<string, object?>>.
// and expect users to provide unique keys.
// Note: It is possible that we allow users
// to override this exporter feature. So not blocking
// empty/{OriginalFormat} in the SDK itself.
}
else
{
AddAttribute(otlpLog, scopeItem, attributeCountLimit, attributeValueLengthLimit);
}
}
}
}
catch (Exception ex)
{
OpenTelemetryProtocolExporterEventSource.Log.CouldNotTranslateLogRecord(ex.Message);
}
return otlpLogRecord;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void AddAttribute(OtlpLogs.LogRecord logRecord, KeyValuePair<string, object?> attribute, int maxAttributeCount, int? maxValueLength)
{
var logRecordAttributes = logRecord.Attributes;
if (logRecordAttributes.Count == maxAttributeCount)
{
logRecord.DroppedAttributesCount++;
}
else
{
OtlpTagWriter.Instance.TryWriteTag(ref logRecordAttributes, attribute, maxValueLength);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void AddStringAttribute(OtlpLogs.LogRecord logRecord, string key, string? value, int maxAttributeCount, int? maxValueLength)
{
var attributeItem = new KeyValuePair<string, object?>(key, value);
AddAttribute(logRecord, attributeItem, maxAttributeCount, maxValueLength);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void AddIntAttribute(OtlpLogs.LogRecord logRecord, string key, int value, int maxAttributeCount)
{
var attributeItem = new KeyValuePair<string, object?>(key, value);
AddAttribute(logRecord, attributeItem, maxAttributeCount, maxValueLength: null);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static OtlpLogs.SeverityNumber GetSeverityNumber(LogRecordSeverity? severity)
{
if (!severity.HasValue)
{
return OtlpLogs.SeverityNumber.Unspecified;
}
return (OtlpLogs.SeverityNumber)(int)severity.Value;
}
}