-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhny.js
252 lines (228 loc) · 7.35 KB
/
hny.js
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
import { HoneycombWebSDK } from "@honeycombio/opentelemetry-web";
import { getWebAutoInstrumentations } from "@opentelemetry/auto-instrumentations-web";
import { trace, context } from "@opentelemetry/api";
import {
ATTR_EXCEPTION_MESSAGE,
ATTR_EXCEPTION_STACKTRACE,
ATTR_EXCEPTION_TYPE,
} from "@opentelemetry/semantic-conventions";
const MY_VERSION = "0.10.35";
function initializeTracing(
params /* { apiKey: string, serviceName: string } */
) {
if (!params) {
params = {};
}
if (!params.apiKey) {
throw new Error(
"Usage: initializeTracing({ apiKey: 'honeycomb api key', serviceName: 'name of this service' })"
);
}
if (!params.serviceName) {
console.log(
"No service name provided to initializeTracing. Defaulting to unknown_service"
);
params.serviceName = "unknown_service";
}
function addContentLengthToSpan(span, resource) {
// this works for document-load.
const encodedLength = resource.encodedBodySize;
if (encodedLength !== undefined) {
span.setAttribute("http.request_content_length", encodedLength); // SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH
}
const decodedLength = resource.decodedBodySize;
if (decodedLength !== undefined && encodedLength !== decodedLength) {
span.setAttribute(
"http.response_content_length_uncompressed", //SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,
decodedLength
);
}
}
const configDefaults = {
ignoreNetworkEvents: true,
// propagateTraceHeaderCorsUrls: [
// /.+/g, // Regex to match your backend URLs. Update to the domains you wish to include.
// ]
};
const sdk = new HoneycombWebSDK({
// endpoint: "https://api.eu1.honeycomb.io/v1/traces", // Send to EU instance of Honeycomb. Defaults to sending to US instance.
localVisualizations: params.debug,
instrumentations: [
getWebAutoInstrumentations({
// Loads custom configuration for xml-http-request instrumentation.
"@opentelemetry/instrumentation-xml-http-request": configDefaults,
"@opentelemetry/instrumentation-fetch": configDefaults,
"@opentelemetry/instrumentation-document-load": {
applyCustomAttributesOnSpan: {
resourceFetch: addContentLengthToSpan,
},
...configDefaults,
},
}),
],
...params,
});
sdk.start();
if (params.debug) {
sendTestSpan();
}
if (params.provideOneLinkToHoneycomb) {
const tracesEndpoint = params.endpoint || "https://api.honeycomb.io";
const apiOrigin = new URL(tracesEndpoint).origin;
const authEndpoint = apiOrigin + "/1/auth";
const uiOrigin = apiOrigin.replace("api", "ui");
const datasetSlug = params.serviceName || "unknown_service";
fetch(authEndpoint, { headers: { "X-Honeycomb-Team": params.apiKey } })
.then((result) => result.json())
.then((data) => {
const datasetQueryUrl = `${uiOrigin}/${data.team.slug}/environments/${data.environment.slug}/datasets/${datasetSlug}`;
console.log(`Query your traces: ${datasetQueryUrl}`);
});
}
// TODO: Can i get parcel to import a json file?
console.log(
`Hny-otel-web tracing initialized, ${MY_VERSION} at last update of this message`
);
}
function sendTestSpan() {
const span = getTracer({
name: "hny-otel-web test",
version: MY_VERSION,
}).startSpan("test span");
console.log("Sending test span", span.spanContext());
span.end();
}
function activeSpanContext() {
return trace.getActiveSpan()?.spanContext();
}
function setAttributes(attributes) {
const span = trace.getActiveSpan();
span && span.setAttributes(attributes); // maybe there is no active span, nbd
}
function getTracer(inputTracer) {
let tracerName, tracerVersion;
if (typeof inputTracer === "string") {
tracerName = inputTracer;
} else {
tracerName = inputTracer.name || "missing tracer name";
tracerVersion = inputTracer.version;
}
return trace.getTracer(tracerName, tracerVersion);
}
function inSpan(inputTracer, spanName, fn, context) {
if (fn === undefined || typeof fn !== "function") {
throw new Error("USAGE: inSpan(tracerName, spanName, () => { ... })");
}
return getTracer(inputTracer).startActiveSpan(
spanName,
{},
context || null,
(span) => {
try {
return fn(span);
} catch (err) {
span.setStatus({
code: 2, //SpanStatusCode.ERROR,
message: err.message,
});
span.recordException(err);
throw err;
} finally {
span.end();
}
}
);
}
async function inSpanAsync(inputTracer, spanName, fn, context) {
if (fn === undefined) {
console.log(
"USAGE: inSpanAsync(tracerName, spanName, async () => { ... })"
);
}
return getTracer(inputTracer).startActiveSpan(
spanName,
{},
context,
async (span) => {
try {
return await fn(span);
} catch (err) {
span.setStatus({
code: 2, // trace.SpanStatusCode.ERROR,
message: err.message,
});
span.recordException(err);
throw err;
} finally {
span.end();
}
}
);
}
function recordException(exception, additionalAttributes) {
const span = trace.getActiveSpan();
if (!span) {
return;
}
// I took this from the sdk-trace-base, except I'm gonna support additional attributes.
// https://github.com/open-telemetry/opentelemetry-js/blob/90afa2850c0690f7a18ecc511c04927a3183490b/packages/opentelemetry-sdk-trace-base/src/Span.ts#L321
const attributes = {};
if (typeof exception === "string") {
attributes[ATTR_EXCEPTION_MESSAGE] = exception;
} else if (exception) {
if (exception.code) {
attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();
} else if (exception.name) {
attributes[ATTR_EXCEPTION_TYPE] = exception.name;
}
if (exception.message) {
attributes[ATTR_EXCEPTION_MESSAGE] = exception.message;
}
if (exception.stack) {
attributes[ATTR_EXCEPTION_STACKTRACE] = exception.stack;
}
}
const allAttributes = { ...attributes, ...additionalAttributes };
span.addEvent("exception", allAttributes);
span.setStatus({
code: 2, // SpanStatusCode.ERROR,
message: attributes[ATTR_EXCEPTION_MESSAGE],
});
}
function addSpanEvent(message, attributes) {
const span = trace.getActiveSpan();
span?.addEvent(message, attributes);
}
function inChildSpan(inputTracer, spanName, spanContext, fn) {
if (
!!spanContext &&
(!spanContext.spanId ||
!spanContext.traceId ||
spanContext.traceFlags === undefined)
) {
console.log(
"inChildSpan: the third argument should be a spanContext (or undefined to use the active context)"
);
}
const usefulContext = !!spanContext
? trace.setSpanContext(context.active(), spanContext)
: context.active();
return inSpan(inputTracer, spanName, fn, usefulContext);
}
/* I'm exporting 'trace' here, but I have a feeling some of the functionality on it is stripped off.
* getActiveSpan() was missing, when I tried to use that outside of this project, while this project was not
* using it.
* Someday, don't export 'trace' because it is a lie. Or do, but document which parts of TraceAPI are gonna be on it.
*/
export const Hny = {
initializeTracing,
setAttributes,
inSpan,
inSpanAsync,
recordException,
addSpanEvent,
activeSpanContext,
inChildSpan,
};
// Now for the REAL export
window.Hny = Hny;