-
Notifications
You must be signed in to change notification settings - Fork 37
/
ActivitySourceExtensions.cs
83 lines (71 loc) · 2.61 KB
/
ActivitySourceExtensions.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
using System.Diagnostics;
using EventStore.Diagnostics;
using EventStore.Diagnostics.Telemetry;
using EventStore.Diagnostics.Tracing;
namespace EventStore.Client.Diagnostics;
static class ActivitySourceExtensions {
public static async ValueTask<T> TraceClientOperation<T>(
this ActivitySource source,
Func<ValueTask<T>> tracedOperation,
string operationName,
ActivityTagsCollection? tags = null
) {
using var activity = StartActivity(source, operationName, ActivityKind.Client, tags, Activity.Current?.Context);
try {
var res = await tracedOperation().ConfigureAwait(false);
activity?.StatusOk();
return res;
} catch (Exception ex) {
activity?.StatusError(ex);
throw;
}
}
public static void TraceSubscriptionEvent(
this ActivitySource source,
string? subscriptionId,
ResolvedEvent resolvedEvent,
ChannelInfo channelInfo,
EventStoreClientSettings settings,
UserCredentials? userCredentials
) {
if (source.HasNoActiveListeners())
return;
var parentContext = resolvedEvent.Event.Metadata.ExtractPropagationContext();
if (parentContext == default(ActivityContext)) return;
var tags = new ActivityTagsCollection()
.WithRequiredTag(TelemetryTags.EventStore.Stream, resolvedEvent.OriginalEvent.EventStreamId)
.WithOptionalTag(TelemetryTags.EventStore.SubscriptionId, subscriptionId)
.WithRequiredTag(TelemetryTags.EventStore.EventId, resolvedEvent.OriginalEvent.EventId.ToString())
.WithRequiredTag(TelemetryTags.EventStore.EventType, resolvedEvent.OriginalEvent.EventType)
// Ensure consistent server.address attribute when connecting to cluster via dns discovery
.WithGrpcChannelServerTags(channelInfo)
.WithClientSettingsServerTags(settings)
.WithOptionalTag(
TelemetryTags.Database.User,
userCredentials?.Username ?? settings.DefaultCredentials?.Username
);
StartActivity(source, TracingConstants.Operations.Subscribe, ActivityKind.Consumer, tags, parentContext)
?.Dispose();
}
static Activity? StartActivity(
this ActivitySource source,
string operationName, ActivityKind activityKind, ActivityTagsCollection? tags = null,
ActivityContext? parentContext = null
) {
if (source.HasNoActiveListeners())
return null;
(tags ??= new ActivityTagsCollection())
.WithRequiredTag(TelemetryTags.Database.System, "eventstoredb")
.WithRequiredTag(TelemetryTags.Database.Operation, operationName);
return source
.CreateActivity(
operationName,
activityKind,
parentContext ?? default,
tags,
idFormat: ActivityIdFormat.W3C
)
?.Start();
}
static bool HasNoActiveListeners(this ActivitySource source) => !source.HasListeners();
}