-
Notifications
You must be signed in to change notification settings - Fork 206
/
Copy pathTransaction.cs
724 lines (610 loc) · 26.3 KB
/
Transaction.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
// Licensed to Elasticsearch B.V under
// one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Elastic.Apm.Api;
using Elastic.Apm.Api.Constraints;
using Elastic.Apm.Config;
using Elastic.Apm.DistributedTracing;
using Elastic.Apm.Helpers;
using Elastic.Apm.Logging;
using Elastic.Apm.Report;
using Elastic.Apm.ServerInfo;
using Elastic.Apm.Libraries.Newtonsoft.Json;
using Elastic.Apm.Metrics.MetricsProvider;
namespace Elastic.Apm.Model
{
internal class Transaction : ITransaction
{
private static readonly string ApmTransactionActivityName = "ElasticApm.Transaction";
internal readonly TraceState _traceState;
internal readonly ConcurrentDictionary<SpanTimerKey, SpanTimer> SpanTimings = new();
/// <summary>
/// The agent also starts an Activity when a transaction is started and stops it when the transaction ends.
/// The TraceId of this activity is always the same as the TraceId of the transaction.
/// With this, in case Activity.Current is null, the agent will set it and when the next Activity gets created it'll
/// have this activity as its parent and the TraceId will flow to all Activity instances.
/// </summary>
private readonly Activity _activity;
private readonly IApmServerInfo _apmServerInfo;
private readonly Lazy<Context> _context = new Lazy<Context>();
private readonly ICurrentExecutionSegmentsContainer _currentExecutionSegmentsContainer;
private readonly IApmLogger _logger;
private readonly IPayloadSender _sender;
private readonly BreakdownMetricsProvider _breakdownMetricsProvider;
[JsonConstructor]
// ReSharper disable once UnusedMember.Local - this constructor is meant for serialization
private Transaction(Context context, string name, string type, double duration, long timestamp, string id, string traceId, string parentId,
bool isSampled, string result, SpanCount spanCount
)
{
_context = new Lazy<Context>(() => context);
Name = name;
Duration = duration;
Timestamp = timestamp;
Type = type;
Id = id;
TraceId = traceId;
ParentId = parentId;
IsSampled = isSampled;
Result = result;
SpanCount = spanCount;
}
// This constructor is used only by tests that don't care about sampling and distributed tracing
internal Transaction(ApmAgent agent, string name, string type, long? timestamp = null)
: this(agent.Logger, name, type, new Sampler(1.0), null, agent.PayloadSender, agent.ConfigStore.CurrentSnapshot,
agent.TracerInternal.CurrentExecutionSegmentsContainer, null, null, timestamp: timestamp) { }
/// <summary>
/// Creates a new transaction
/// </summary>
/// <param name="logger">The logger which logs debug information during the transaction creation process</param>
/// <param name="name">The name of the transaction</param>
/// <param name="type">The type of the transaction</param>
/// <param name="sampler">The sampler implementation which makes the sampling decision</param>
/// <param name="distributedTracingData">Distributed tracing data, in case this transaction is part of a distributed trace</param>
/// <param name="sender">The IPayloadSender implementation which will record this transaction</param>
/// <param name="configSnapshot">The current configuration snapshot which contains the up-do-date config setting values</param>
/// <param name="currentExecutionSegmentsContainer" />
/// The ExecutionSegmentsContainer which makes sure this transaction flows
/// <param name="apmServerInfo">Component to fetch info about APM Server (e.g. APM Server version)</param>
/// <param name="breakdownMetricsProvider">The <see cref="BreakdownMetricsProvider"/> instance which will capture the breakdown metrics</param>
/// <param name="ignoreActivity">
/// If set the transaction will ignore Activity.Current and it's trace id,
/// otherwise the agent will try to keep ids in-sync across async work-flows
/// </param>
/// <param name="timestamp">
/// The timestamp of the transaction. If it's <code>null</code> then the current timestamp
/// will be captured, which is typically the desired behaviour. Setting the timestamp to a specific value is typically
/// useful for testing.
/// </param>
internal Transaction(
IApmLogger logger,
string name,
string type,
Sampler sampler,
DistributedTracingData distributedTracingData,
IPayloadSender sender,
IConfigSnapshot configSnapshot,
ICurrentExecutionSegmentsContainer currentExecutionSegmentsContainer,
IApmServerInfo apmServerInfo,
BreakdownMetricsProvider breakdownMetricsProvider,
bool ignoreActivity = false,
long? timestamp = null
)
{
ConfigSnapshot = configSnapshot;
Timestamp = timestamp ?? TimeUtils.TimestampNow();
_logger = logger?.Scoped(nameof(Transaction));
_apmServerInfo = apmServerInfo;
_sender = sender;
_currentExecutionSegmentsContainer = currentExecutionSegmentsContainer;
_breakdownMetricsProvider = breakdownMetricsProvider;
Name = name;
HasCustomName = false;
Type = type;
// For each new transaction, start an Activity if we're not ignoring them.
// If Activity.Current is not null, the started activity will be a child activity,
// so the traceid and tracestate of the parent will flow to it.
if (!ignoreActivity)
_activity = StartActivity();
var isSamplingFromDistributedTracingData = false;
if (distributedTracingData == null)
{
// We consider a newly created transaction **without** explicitly passed distributed tracing data
// to be a root transaction.
// Ignore the created activity ActivityTraceFlags because it starts out without setting the IsSampled flag,
// so relying on that would mean a transaction is never sampled.
if (_activity != null)
{
// If an activity was created, reuse its id
Id = _activity.SpanId.ToHexString();
TraceId = _activity.TraceId.ToHexString();
var idBytesFromActivity = new Span<byte>(new byte[16]);
_activity.TraceId.CopyTo(idBytesFromActivity);
// Read right most bits. From W3C TraceContext: "it is important for trace-id to carry "uniqueness" and "randomness"
// in the right part of the trace-id..."
idBytesFromActivity = idBytesFromActivity.Slice(8);
_traceState = new TraceState();
// If activity has a tracestate, populate the transaction tracestate with it.
if (!string.IsNullOrEmpty(_activity.TraceStateString))
_traceState.AddTextHeader(_activity.TraceStateString);
IsSampled = sampler.DecideIfToSample(idBytesFromActivity.ToArray());
// In the unlikely event that tracestate populated from activity contains an es vendor key, the tracestate
// is mutated to set the sample rate defined by the sampler, because we consider a transaction without
// explicitly passed distributedTracingData to be a **root** transaction. The end result
// is that activity tracestate will be propagated, along with the sample rate defined by this transaction.
if (IsSampled)
{
SampleRate = sampler.Rate;
_traceState.SetSampleRate(sampler.Rate);
}
else
{
SampleRate = 0;
_traceState.SetSampleRate(0);
}
// sync the activity tracestate with the tracestate of the transaction
_activity.TraceStateString = _traceState.ToTextHeader();
}
else
{
// If no activity is created, create new random ids
var idBytes = new byte[8];
Id = RandomGenerator.GenerateRandomBytesAsString(idBytes);
IsSampled = sampler.DecideIfToSample(idBytes);
idBytes = new byte[16];
TraceId = RandomGenerator.GenerateRandomBytesAsString(idBytes);
if (IsSampled)
{
_traceState = new TraceState(sampler.Rate);
SampleRate = sampler.Rate;
}
else
{
_traceState = new TraceState(0);
SampleRate = 0;
}
}
// ParentId could be also set here, but currently in the UI each trace must start with a transaction where the ParentId is null,
// so to avoid https://github.com/elastic/apm-agent-dotnet/issues/883 we don't set it yet.
}
else
{
var idBytes = new byte[8];
if (_activity != null)
{
Id = _activity.SpanId.ToHexString();
_activity.SpanId.CopyTo(new Span<byte>(idBytes));
// try to set the parent id and tracestate on the created activity, based on passed distributed tracing data.
// This is so that the distributed tracing data will flow to any child activities
try
{
_activity.SetParentId(
ActivityTraceId.CreateFromString(distributedTracingData.TraceId.AsSpan()),
ActivitySpanId.CreateFromString(distributedTracingData.ParentId.AsSpan()),
distributedTracingData.FlagRecorded ? ActivityTraceFlags.Recorded : ActivityTraceFlags.None);
if (distributedTracingData.HasTraceState)
_activity.TraceStateString = distributedTracingData.TraceState.ToTextHeader();
}
catch (Exception e)
{
_logger.Error()?.LogException(e, "Error setting trace context on created activity");
}
}
else
Id = RandomGenerator.GenerateRandomBytesAsString(idBytes);
TraceId = distributedTracingData.TraceId;
ParentId = distributedTracingData.ParentId;
isSamplingFromDistributedTracingData = true;
_traceState = distributedTracingData.TraceState;
// If TraceContextIgnoreSampledFalse is set and the upstream service is not from our agent (aka no sample rate set)
// ignore the sampled flag and make a new sampling decision.
if (configSnapshot.TraceContextIgnoreSampledFalse && (distributedTracingData.TraceState == null
|| !distributedTracingData.TraceState.SampleRate.HasValue && !distributedTracingData.FlagRecorded))
{
IsSampled = sampler.DecideIfToSample(idBytes);
_traceState?.SetSampleRate(sampler.Rate);
}
else
IsSampled = distributedTracingData.FlagRecorded;
// If there is no tracestate or no valid "es" vendor entry with an "s" (sample rate) attribute, then the agent must
// omit sample rate from non-root transactions and their spans.
// See https://github.com/elastic/apm/blob/master/specs/agents/tracing-sampling.md#propagation
if (_traceState?.SampleRate is null)
SampleRate = null;
else
SampleRate = _traceState.SampleRate.Value;
}
// Also mark the sampling decision on the Activity
if (IsSampled && _activity != null)
_activity.ActivityTraceFlags |= ActivityTraceFlags.Recorded;
SpanCount = new SpanCount();
_currentExecutionSegmentsContainer.CurrentTransaction = this;
if (isSamplingFromDistributedTracingData)
{
_logger.Trace()
?.Log("New Transaction instance created: {Transaction}. " +
"IsSampled ({IsSampled}) and SampleRate ({SampleRate}) is based on incoming distributed tracing data ({DistributedTracingData})."
+
" Start time: {Time} (as timestamp: {Timestamp})",
this, IsSampled, SampleRate, distributedTracingData, TimeUtils.FormatTimestampForLog(Timestamp), Timestamp);
}
else
{
_logger.Trace()
?.Log("New Transaction instance created: {Transaction}. " +
"IsSampled ({IsSampled}) is based on the given sampler ({Sampler})." +
" Start time: {Time} (as timestamp: {Timestamp})",
this, IsSampled, sampler, TimeUtils.FormatTimestampForLog(Timestamp), Timestamp);
}
}
private bool _isEnded;
private string _name;
/// <summary>
/// In general if there is an error on the span, the outcome will be <code> Outcome.Failure </code> otherwise it'll be
/// <code> Outcome.Success </code>..
/// There are some exceptions to this (see spec:
/// https://github.com/elastic/apm/blob/master/specs/agents/tracing-spans.md#span-outcome) when it can be
/// <code>Outcome.Unknown</code>/>.
/// Use <see cref="_outcomeChangedThroughApi" /> to check if it was specifically set to <code>Outcome.Unknown</code>, or if
/// it's just the default value.
/// </summary>
private Outcome _outcome;
private bool _outcomeChangedThroughApi;
internal ChildDurationTimer ChildDurationTimer { get; } = new();
/// <summary>
/// Holds configuration snapshot (which is immutable) that was current when this transaction started.
/// We would like transaction data to be consistent and not to be affected by possible changes in agent's configuration
/// between the start and the end of the transaction. That is why the way all the data is collected for the transaction
/// and its spans is controlled by this configuration snapshot.
/// </summary>
[JsonIgnore]
internal IConfigSnapshot ConfigSnapshot { get; }
/// <summary>
/// Any arbitrary contextual information regarding the event, captured by the agent, optionally provided by the user.
/// <seealso cref="ShouldSerializeContext" />
/// </summary>
public Context Context => _context.Value;
[JsonIgnore]
public Dictionary<string, string> Custom => Context.Custom;
/// <inheritdoc />
/// <summary>
/// The duration of the transaction in ms with 3 decimal points.
/// If it's not set (HasValue returns false) then the value
/// is automatically calculated when <see cref="End" /> is called.
/// </summary>
/// <value>The duration.</value>
public double? Duration { get; set; }
/// <summary>
/// If true, then the transaction name was modified by external code, and transaction name should not be changed
/// or "fixed" automatically.
/// </summary>
[JsonIgnore]
internal bool HasCustomName { get; private set; }
[MaxLength]
public string Id { get; }
[JsonIgnore]
internal bool IsContextCreated => _context.IsValueCreated;
[JsonProperty("sampled")]
public bool IsSampled { get; }
[JsonIgnore]
[Obsolete(
"Instead of this dictionary, use the `SetLabel` method which supports more types than just string. This property will be removed in a future release.")]
public Dictionary<string, string> Labels => Context.Labels;
[MaxLength]
public string Name
{
get => _name;
set
{
HasCustomName = true;
_name = value;
}
}
/// <summary>
/// The outcome of the transaction: success, failure, or unknown.
/// This is similar to 'result', but has a limited set of permitted values describing the success or failure of the
/// transaction from the service's perspective.
/// This field can be used for calculating error rates for incoming requests.
/// </summary>
public Outcome Outcome
{
get => _outcome;
set
{
_outcomeChangedThroughApi = true;
_outcome = value;
}
}
[JsonIgnore]
public DistributedTracingData OutgoingDistributedTracingData => new DistributedTracingData(TraceId, Id, IsSampled, _traceState);
[MaxLength]
[JsonProperty("parent_id")]
public string ParentId { get; set; }
/// <inheritdoc />
/// <summary>
/// A string describing the result of the transaction.
/// This is typically the HTTP status code, or e.g. "success" for a background task.
/// </summary>
/// <value>The result.</value>
[MaxLength]
public string Result { get; set; }
/// <summary>
/// Captures the sample rate of the agent when this transaction was created.
/// </summary>
[JsonProperty("sample_rate")]
internal double? SampleRate { get; }
internal double SelfDuration => Duration.HasValue ? Duration.Value - ChildDurationTimer.Duration : 0;
internal Service Service;
[JsonProperty("span_count")]
public SpanCount SpanCount { get; set; }
/// <summary>
/// Recorded time of the event, UTC based and formatted as microseconds since Unix epoch
/// </summary>
public long Timestamp { get; }
[MaxLength]
[JsonProperty("trace_id")]
public string TraceId { get; }
[MaxLength]
public string Type { get; set; }
private Activity StartActivity()
{
var activity = new Activity(ApmTransactionActivityName);
activity.SetIdFormat(ActivityIdFormat.W3C);
activity.Start();
return activity;
}
/// <inheritdoc />
public void SetService(string serviceName, string serviceVersion)
{
if (Context.Service == null)
Context.Service = new Service(serviceName, serviceVersion);
else
{
Context.Service.Name = serviceName;
Context.Service.Version = serviceVersion;
}
}
public string EnsureParentId()
{
if (!string.IsNullOrEmpty(ParentId))
return ParentId;
var idBytes = new byte[8];
ParentId = RandomGenerator.GenerateRandomBytesAsString(idBytes);
_logger?.Debug()?.Log("Setting ParentId to transaction, {transaction}", this);
return ParentId;
}
/// <summary>
/// Method to conditionally serialize <see cref="Context" /> because context should be serialized only when the transaction
/// is sampled.
/// See
/// <a href="https://www.newtonsoft.com/json/help/html/ConditionalProperties.htm">the relevant Json.NET Documentation</a>
/// </summary>
public bool ShouldSerializeContext() => IsSampled;
public override string ToString() => new ToStringBuilder(nameof(Transaction))
{
{ nameof(Id), Id },
{ nameof(TraceId), TraceId },
{ nameof(ParentId), ParentId },
{ nameof(Name), Name },
{ nameof(Type), Type },
{ nameof(Outcome), Outcome },
{ nameof(IsSampled), IsSampled }
}.ToString();
/// <summary>
/// When the transaction has ended and before being queued to send to APM server
/// </summary>
public event EventHandler Ended;
public void End()
{
// If the outcome is still unknown and it was not specifically set to unknown, then it's success
if (Outcome == Outcome.Unknown && !_outcomeChangedThroughApi)
Outcome = Outcome.Success;
if (Duration.HasValue)
{
_logger.Trace()
?.Log("Ended {Transaction} (with Duration already set)." +
" Start time: {Time} (as timestamp: {Timestamp}), Duration: {Duration}ms",
this, TimeUtils.FormatTimestampForLog(Timestamp), Timestamp, Duration);
ChildDurationTimer.OnSpanEnd((long)(Timestamp + Duration.Value * 1000));
}
else
{
Assertion.IfEnabled?.That(!_isEnded,
$"Transaction's Duration doesn't have value even though {nameof(End)} method was already called." +
$" It contradicts the invariant enforced by {nameof(End)} method - Duration should have value when {nameof(End)} method exits" +
$" and {nameof(_isEnded)} field is set to true only when {nameof(End)} method exits." +
$" Context: this: {this}; {nameof(_isEnded)}: {_isEnded}");
var endTimestamp = TimeUtils.TimestampNow();
ChildDurationTimer.OnSpanEnd(endTimestamp);
Duration = TimeUtils.DurationBetweenTimestamps(Timestamp, endTimestamp);
_logger.Trace()
?.Log("Ended {Transaction}. Start time: {Time} (as timestamp: {Timestamp})," +
" End time: {Time} (as timestamp: {Timestamp}), Duration: {Duration}ms",
this, TimeUtils.FormatTimestampForLog(Timestamp), Timestamp,
TimeUtils.FormatTimestampForLog(endTimestamp), endTimestamp, Duration);
}
_activity?.Stop();
var isFirstEndCall = !_isEnded;
_isEnded = true;
if (!isFirstEndCall)
return;
if (SpanTimings.ContainsKey(SpanTimerKey.AppSpanType))
SpanTimings[SpanTimerKey.AppSpanType].IncrementTimer(SelfDuration);
else
SpanTimings.TryAdd(SpanTimerKey.AppSpanType, new SpanTimer(SelfDuration));
_breakdownMetricsProvider?.CaptureTransaction(this);
var handler = Ended;
handler?.Invoke(this, EventArgs.Empty);
Ended = null;
_sender.QueueTransaction(this);
_currentExecutionSegmentsContainer.CurrentTransaction = null;
}
public bool TryGetLabel<T>(string key, out T value)
{
if (Context.InternalLabels.Value.InnerDictionary.TryGetValue(key, out var label))
{
if (label?.Value is T t)
{
value = t;
return true;
}
}
value = default;
return false;
}
public ISpan StartSpan(string name, string type, string subType = null, string action = null)
{
if (ConfigSnapshot.Enabled && ConfigSnapshot.Recording)
return StartSpanInternal(name, type, subType, action);
return new NoopSpan(name, type, subType, action, _currentExecutionSegmentsContainer, Id, TraceId);
}
internal Span StartSpanInternal(string name, string type, string subType = null, string action = null,
InstrumentationFlag instrumentationFlag = InstrumentationFlag.None, bool captureStackTraceOnStart = false, long? timestamp = null
)
{
var retVal = new Span(name, type, Id, TraceId, this, _sender, _logger, _currentExecutionSegmentsContainer, _apmServerInfo,
instrumentationFlag: instrumentationFlag, captureStackTraceOnStart: captureStackTraceOnStart, timestamp: timestamp);
ChildDurationTimer.OnChildStart(retVal.Timestamp);
if (!string.IsNullOrEmpty(subType))
retVal.Subtype = subType;
if (!string.IsNullOrEmpty(action))
retVal.Action = action;
_logger.Trace()?.Log("Starting {SpanDetails}", retVal.ToString());
return retVal;
}
public void CaptureException(Exception exception, string culprit = null, bool isHandled = false, string parentId = null,
Dictionary<string, Label> labels = null
)
=> ExecutionSegmentCommon.CaptureException(
exception,
_logger,
_sender,
this,
ConfigSnapshot,
this,
_apmServerInfo,
culprit,
isHandled,
parentId,
labels
);
public void CaptureError(string message, string culprit, StackFrame[] frames, string parentId = null, Dictionary<string, Label> labels = null)
=> ExecutionSegmentCommon.CaptureError(
message,
culprit,
frames,
_sender,
_logger,
this,
ConfigSnapshot,
this,
_apmServerInfo,
parentId,
labels
);
public void CaptureSpan(string name, string type, Action<ISpan> capturedAction, string subType = null, string action = null)
=> ExecutionSegmentCommon.CaptureSpan(StartSpanInternal(name, type, subType, action), capturedAction);
public void CaptureSpan(string name, string type, Action capturedAction, string subType = null, string action = null)
=> ExecutionSegmentCommon.CaptureSpan(StartSpanInternal(name, type, subType, action), capturedAction);
public T CaptureSpan<T>(string name, string type, Func<ISpan, T> func, string subType = null, string action = null)
=> ExecutionSegmentCommon.CaptureSpan(StartSpanInternal(name, type, subType, action), func);
public T CaptureSpan<T>(string name, string type, Func<T> func, string subType = null, string action = null)
=> ExecutionSegmentCommon.CaptureSpan(StartSpanInternal(name, type, subType, action), func);
public Task CaptureSpan(string name, string type, Func<Task> func, string subType = null, string action = null)
=> ExecutionSegmentCommon.CaptureSpan(StartSpanInternal(name, type, subType, action), func);
public Task CaptureSpan(string name, string type, Func<ISpan, Task> func, string subType = null, string action = null)
=> ExecutionSegmentCommon.CaptureSpan(StartSpanInternal(name, type, subType, action), func);
public Task<T> CaptureSpan<T>(string name, string type, Func<Task<T>> func, string subType = null, string action = null)
=> ExecutionSegmentCommon.CaptureSpan(StartSpanInternal(name, type, subType, action), func);
public Task<T> CaptureSpan<T>(string name, string type, Func<ISpan, Task<T>> func, string subType = null, string action = null)
=> ExecutionSegmentCommon.CaptureSpan(StartSpanInternal(name, type, subType, action), func);
internal static string StatusCodeToResult(string protocolName, int statusCode) => $"{protocolName} {statusCode.ToString()[0]}xx";
/// <summary>
/// Determines a name from the route values
/// </summary>
/// <remarks>
/// Based on: https://github.com/Microsoft/ApplicationInsights-aspnetcore
/// </remarks>
internal static string GetNameFromRouteContext(IDictionary<string, object> routeValues)
{
if (routeValues.Count <= 0)
return null;
string name = null;
var count = routeValues.TryGetValue("controller", out var controller) ? 1 : 0;
var controllerString = controller == null ? string.Empty : controller.ToString();
if (!string.IsNullOrEmpty(controllerString))
{
// Check for MVC areas
string areaString = null;
if (routeValues.TryGetValue("area", out var area))
{
count++;
areaString = area.ToString();
}
name = !string.IsNullOrEmpty(areaString)
? areaString + "/" + controllerString
: controllerString;
count = routeValues.TryGetValue("action", out var action) ? count + 1 : count;
var actionString = action == null ? string.Empty : action.ToString();
if (!string.IsNullOrEmpty(actionString))
name += "/" + actionString;
// if there are no other key/values other than area/controller/action, skip parsing parameters
if (routeValues.Keys.Count == count)
return name;
// Add parameters
var sortedKeys = routeValues.Keys
.Where(key =>
!string.Equals(key, "area", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(key, "controller", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(key, "action", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(key, "!__route_group", StringComparison.OrdinalIgnoreCase))
.OrderBy(key => key, StringComparer.OrdinalIgnoreCase)
.ToArray();
if (sortedKeys.Length <= 0)
return name;
var arguments = string.Join(@"/", sortedKeys);
name += " {" + arguments + "}";
}
else
{
routeValues.TryGetValue("page", out var page);
var pageString = page == null ? string.Empty : page.ToString();
if (!string.IsNullOrEmpty(pageString))
name = pageString;
}
return name;
}
public void CaptureErrorLog(ErrorLog errorLog, string parentId = null, Exception exception = null, Dictionary<string, Label> labels = null)
=> ExecutionSegmentCommon.CaptureErrorLog(
errorLog,
_sender,
_logger,
this,
ConfigSnapshot,
this,
null,
_apmServerInfo,
exception,
labels
);
public void SetLabel(string key, string value)
=> _context.Value.InternalLabels.Value.InnerDictionary[key] = value;
public void SetLabel(string key, bool value)
=> _context.Value.InternalLabels.Value.InnerDictionary[key] = value;
public void SetLabel(string key, double value)
=> _context.Value.InternalLabels.Value.InnerDictionary[key] = value;
public void SetLabel(string key, int value)
=> _context.Value.InternalLabels.Value.InnerDictionary[key] = value;
public void SetLabel(string key, long value)
=> _context.Value.InternalLabels.Value.InnerDictionary[key] = value;
public void SetLabel(string key, decimal value)
=> _context.Value.InternalLabels.Value.InnerDictionary[key] = value;
}
}