forked from open-telemetry/opentelemetry-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSqlEventSourceListener.netfx.cs
181 lines (161 loc) · 6.69 KB
/
SqlEventSourceListener.netfx.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
// <copyright file="SqlEventSourceListener.netfx.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
#if NETFRAMEWORK
using System;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using OpenTelemetry.Trace;
namespace OpenTelemetry.Instrumentation.SqlClient.Implementation
{
/// <summary>
/// .NET Framework SqlClient doesn't emit DiagnosticSource events.
/// We hook into its EventSource if it is available:
/// See: <a href="https://github.com/microsoft/referencesource/blob/3b1eaf5203992df69de44c783a3eda37d3d4cd10/System.Data/System/Data/Common/SqlEventSource.cs#L29">reference source</a>.
/// </summary>
internal class SqlEventSourceListener : EventListener
{
internal const string AdoNetEventSourceName = "Microsoft-AdoNet-SystemData";
internal const int BeginExecuteEventId = 1;
internal const int EndExecuteEventId = 2;
private readonly SqlClientInstrumentationOptions options;
private EventSource eventSource;
public SqlEventSourceListener(SqlClientInstrumentationOptions options = null)
{
this.options = options ?? new SqlClientInstrumentationOptions();
}
public override void Dispose()
{
if (this.eventSource != null)
{
this.DisableEvents(this.eventSource);
}
base.Dispose();
}
protected override void OnEventSourceCreated(EventSource eventSource)
{
if (eventSource?.Name.StartsWith(AdoNetEventSourceName, StringComparison.Ordinal) == true)
{
this.eventSource = eventSource;
this.EnableEvents(eventSource, EventLevel.Informational, (EventKeywords)1);
}
base.OnEventSourceCreated(eventSource);
}
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
try
{
if (eventData.EventId == BeginExecuteEventId)
{
this.OnBeginExecute(eventData);
}
else if (eventData.EventId == EndExecuteEventId)
{
this.OnEndExecute(eventData);
}
}
catch (Exception exc)
{
SqlClientInstrumentationEventSource.Log.UnknownErrorProcessingEvent(nameof(SqlEventSourceListener), nameof(this.OnEventWritten), exc);
}
}
private void OnBeginExecute(EventWrittenEventArgs eventData)
{
/*
Expected payload:
[0] -> ObjectId
[1] -> DataSource
[2] -> Database
[3] -> CommandText ([3] = CommandType == CommandType.StoredProcedure ? CommandText : string.Empty)
*/
if ((eventData?.Payload?.Count ?? 0) < 4)
{
SqlClientInstrumentationEventSource.Log.InvalidPayload(nameof(SqlEventSourceListener), nameof(this.OnBeginExecute));
return;
}
var activity = SqlClientDiagnosticListener.SqlClientActivitySource.StartActivity(SqlClientDiagnosticListener.ActivityName, ActivityKind.Client);
if (activity == null)
{
// There is no listener or it decided not to sample the current request.
return;
}
string databaseName = (string)eventData.Payload[2];
activity.DisplayName = databaseName;
if (activity.IsAllDataRequested)
{
activity.SetTag(SemanticConventions.AttributeDbSystem, SqlClientDiagnosticListener.MicrosoftSqlServerDatabaseSystemName);
activity.SetTag(SemanticConventions.AttributeDbName, databaseName);
this.options.AddConnectionLevelDetailsToActivity((string)eventData.Payload[1], activity);
string commandText = (string)eventData.Payload[3];
if (string.IsNullOrEmpty(commandText))
{
activity.SetTag(SpanAttributeConstants.DatabaseStatementTypeKey, nameof(CommandType.Text));
}
else
{
activity.SetTag(SpanAttributeConstants.DatabaseStatementTypeKey, nameof(CommandType.StoredProcedure));
if (this.options.SetStoredProcedureCommandName)
{
activity.SetTag(SemanticConventions.AttributeDbStatement, commandText);
}
}
}
}
private void OnEndExecute(EventWrittenEventArgs eventData)
{
/*
Expected payload:
[0] -> ObjectId
[1] -> CompositeState bitmask (0b001 -> successFlag, 0b010 -> isSqlExceptionFlag , 0b100 -> synchronousFlag)
[2] -> SqlExceptionNumber
*/
if ((eventData?.Payload?.Count ?? 0) < 3)
{
SqlClientInstrumentationEventSource.Log.InvalidPayload(nameof(SqlEventSourceListener), nameof(this.OnEndExecute));
return;
}
var activity = Activity.Current;
if (activity?.Source != SqlClientDiagnosticListener.SqlClientActivitySource)
{
return;
}
try
{
if (activity.IsAllDataRequested)
{
int compositeState = (int)eventData.Payload[1];
if ((compositeState & 0b001) == 0b001)
{
activity.SetStatus(Status.Unset);
}
else if ((compositeState & 0b010) == 0b010)
{
activity.SetStatus(Status.Error.WithDescription($"SqlExceptionNumber {eventData.Payload[2]} thrown."));
}
else
{
activity.SetStatus(Status.Error.WithDescription("Unknown Sql failure."));
}
}
}
finally
{
activity.Stop();
}
}
}
}
#endif