forked from newrelic/newrelic-telemetry-sdk-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNewRelicTraceExporter.cs
300 lines (256 loc) · 11.2 KB
/
NewRelicTraceExporter.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
// Copyright 2020 New Relic, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using NewRelic.OpenTelemetry.Internal;
using NewRelic.Telemetry;
using NewRelic.Telemetry.Tracing;
using NewRelic.Telemetry.Transport;
using OpenTelemetry;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using TelemetrySdk = NewRelic.Telemetry;
namespace NewRelic.OpenTelemetry
{
/// <summary>
/// An exporter used to send Trace/Span information to New Relic.
/// </summary>
internal class NewRelicTraceExporter : BaseExporter<Activity>
{
private const string OTelStatusCodeAttributeName = "otel.status_code";
private const string OTelStatusDescriptionAttributeName = "otel.status_description";
private static readonly HashSet<string> _tagNamesToIgnore = new HashSet<string>
{
OTelStatusCodeAttributeName,
OTelStatusDescriptionAttributeName,
NewRelicConsts.Tracing.AttribNameDurationMs,
NewRelicConsts.Tracing.AttribNameName,
NewRelicConsts.Tracing.AttribNameErrorMsg,
NewRelicConsts.Tracing.AttribSpanKind,
NewRelicConsts.AttributeInstrumentationName,
NewRelicConsts.AttributeInstrumentationVersion,
NewRelicConsts.Tracing.AttribNameParentId,
};
private readonly TraceDataSender _spanDataSender;
private readonly ITelemetryLogger _logger;
private readonly TelemetrySdk.TelemetryConfiguration _config;
/// <summary>
/// Initializes a new instance of the <see cref="NewRelicTraceExporter"/> class.
/// Configures the Trace Exporter accepting configuration settings from an instance of the New Relic Exporter options object.
/// </summary>
/// <param name="options"></param>
public NewRelicTraceExporter(NewRelicExporterOptions options)
: this(options, new SelfDiagnosticsLogger())
{
}
internal NewRelicTraceExporter(NewRelicExporterOptions options, ITelemetryLogger logger)
: this(new TraceDataSender(options.TelemetryConfiguration, logger, "exporter"), options, logger)
{
}
internal NewRelicTraceExporter(TraceDataSender spanDataSender, NewRelicExporterOptions options, ITelemetryLogger logger)
{
_spanDataSender = spanDataSender;
spanDataSender.AddVersionInfo(ProductInfo.Name, ProductInfo.Version);
_config = options.TelemetryConfiguration;
_logger = logger;
}
/// <inheritdoc />
public override ExportResult Export(in Batch<Activity> activityBatch)
{
// Prevent exporter's HTTP operations from being instrumented.
using var scope = SuppressInstrumentationScope.Begin();
var spanBatches = ToNewRelicSpanBatches(activityBatch);
if (spanBatches.Count() == 0)
{
return ExportResult.Success;
}
Response? response = null;
Task.Run(async () => response = await _spanDataSender.SendDataAsync(spanBatches)).GetAwaiter().GetResult();
switch (response?.ResponseStatus)
{
case NewRelicResponseStatus.DidNotSend_NoData:
case NewRelicResponseStatus.Success:
return ExportResult.Success;
case NewRelicResponseStatus.Failure:
default:
return ExportResult.Failure;
}
}
private static string? ActivityKindToString(ActivityKind kind)
{
return kind switch
{
ActivityKind.Consumer => "CONSUMER",
ActivityKind.Client => "CLIENT",
ActivityKind.Internal => "INTERNAL",
ActivityKind.Producer => "PRODUCER",
ActivityKind.Server => "SERVER",
_ => null,
};
}
private static string? StatusCodeToString(StatusCode statusCode)
{
return statusCode switch
{
StatusCode.Error => "Error",
StatusCode.Ok => "Ok",
StatusCode.Unset => "Unset",
_ => null,
};
}
private IEnumerable<NewRelicSpanBatch> ToNewRelicSpanBatches(in Batch<Activity> activityBatch)
{
var spansByResource = GroupByResource(activityBatch);
var spanBatches = new List<NewRelicSpanBatch>(spansByResource.Count);
foreach (var resource in spansByResource)
{
string? serviceName = null;
string? serviceNamespace = null;
Dictionary<string, object>? commonProperties = new Dictionary<string, object>();
commonProperties.Add(NewRelicConsts.AttribNameCollectorName, "newrelic-opentelemetry-exporter");
commonProperties.Add(NewRelicConsts.AttribNameInstrumentationProvider, "opentelemetry");
foreach (var label in resource.Key.Attributes)
{
switch (label.Key)
{
case ResourceSemanticConventions.AttributeServiceName:
serviceName = label.Value as string;
continue;
case ResourceSemanticConventions.AttributeServiceNamespace:
serviceNamespace = label.Value as string;
continue;
}
commonProperties[label.Key] = label.Value;
}
if (!string.IsNullOrWhiteSpace(serviceName))
{
serviceName = serviceNamespace != null
? serviceNamespace + "." + serviceName
: serviceName;
}
else
{
serviceName = _config.ServiceName;
}
if (!string.IsNullOrWhiteSpace(serviceName))
{
commonProperties.Add(NewRelicConsts.Tracing.AttribNameServiceName, serviceName!);
}
var spanBatchCommonProperties = new NewRelicSpanBatchCommonProperties(null, commonProperties);
var spanBatch = new NewRelicSpanBatch(resource.Value, spanBatchCommonProperties);
spanBatches.Add(spanBatch);
}
return spanBatches;
}
private Dictionary<Resource, List<NewRelicSpan>> GroupByResource(in Batch<Activity> activityBatch)
{
var result = new Dictionary<Resource, List<NewRelicSpan>>();
foreach (var activity in activityBatch)
{
var resource = ParentProvider.GetResource();
if (!result.TryGetValue(resource, out var spans))
{
spans = new List<NewRelicSpan>();
result[resource] = spans;
}
try
{
var newRelicSpan = ToNewRelicSpan(activity);
spans.Add(newRelicSpan);
}
catch (Exception ex)
{
var otSpanId = "<unknown>";
try
{
otSpanId = activity.Context.SpanId.ToHexString();
}
catch
{
}
_logger.Error($"Error translating Open Telemetry Span {otSpanId} to New Relic Span.", ex);
}
}
return result;
}
private NewRelicSpan ToNewRelicSpan(Activity openTelemetrySpan)
{
if (openTelemetrySpan == default)
{
throw new ArgumentException(nameof(openTelemetrySpan));
}
if (openTelemetrySpan.Context == default)
{
throw new ArgumentException($"{nameof(openTelemetrySpan)}.Context");
}
// Build attributes with required items
var newRelicSpanAttribs = new Dictionary<string, object>()
{
{ NewRelicConsts.Tracing.AttribNameDurationMs, openTelemetrySpan.Duration.TotalMilliseconds },
};
if (!string.IsNullOrWhiteSpace(openTelemetrySpan.DisplayName))
{
newRelicSpanAttribs.Add(NewRelicConsts.Tracing.AttribNameName, openTelemetrySpan.DisplayName);
}
var status = openTelemetrySpan.GetStatus();
if (status.StatusCode == StatusCode.Error)
{
if (!string.IsNullOrWhiteSpace(status.Description))
{
newRelicSpanAttribs.Add(NewRelicConsts.Tracing.AttribNameErrorMsg, status.Description);
}
else
{
newRelicSpanAttribs.Add(NewRelicConsts.Tracing.AttribNameErrorMsg, "Unspecified error");
}
}
var statusCode = StatusCodeToString(status.StatusCode);
if (status.StatusCode != StatusCode.Unset && statusCode != null)
{
newRelicSpanAttribs.Add(OTelStatusCodeAttributeName, statusCode);
if (!string.IsNullOrWhiteSpace(status.Description))
{
newRelicSpanAttribs.Add(OTelStatusDescriptionAttributeName, status.Description);
}
}
var parentSpanId = openTelemetrySpan.ParentSpanId != default
? openTelemetrySpan.ParentSpanId.ToHexString()
: null;
var spanKind = ActivityKindToString(openTelemetrySpan.Kind);
if (spanKind != null)
{
newRelicSpanAttribs.Add(NewRelicConsts.Tracing.AttribSpanKind, spanKind);
}
var source = openTelemetrySpan.Source;
if (source != null && !string.IsNullOrEmpty(source.Name))
{
newRelicSpanAttribs.Add(NewRelicConsts.AttributeInstrumentationName, openTelemetrySpan.Source.Name);
if (source.Version != null && !string.IsNullOrEmpty(source.Version))
{
newRelicSpanAttribs.Add(NewRelicConsts.AttributeInstrumentationVersion, source.Version);
}
}
if (openTelemetrySpan.TagObjects != null)
{
foreach (var spanAttrib in openTelemetrySpan.TagObjects)
{
if (spanAttrib.Value == null || _tagNamesToIgnore.Contains(spanAttrib.Key))
{
continue;
}
newRelicSpanAttribs[spanAttrib.Key] = spanAttrib.Value;
}
}
var newRelicSpan = new NewRelicSpan(
traceId: openTelemetrySpan.Context.TraceId.ToHexString(),
spanId: openTelemetrySpan.Context.SpanId.ToHexString(),
parentSpanId: parentSpanId,
timestamp: new DateTimeOffset(openTelemetrySpan.StartTimeUtc).ToUnixTimeMilliseconds(),
attributes: newRelicSpanAttribs);
return newRelicSpan;
}
}
}