/
azure-coretracing.sub.ts
72 lines (66 loc) · 2.75 KB
/
azure-coretracing.sub.ts
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
import TelemetryClient = require("../../Library/TelemetryClient");
import { channel, IStandardEvent } from "diagnostic-channel";
import Traceparent = require("../../Library/Traceparent");
import * as Contracts from "../../Declarations/Contracts";
import { Span, AsyncScopeManager } from "../AsyncHooksScopeManager";
let clients: TelemetryClient[] = [];
export const subscriber = (event: IStandardEvent<Span>) => {
const span = event.data;
const spanContext = span.context();
const duration = Math.round(span._duration[0] * 1e3 + span._duration[1] / 1e6);
const id = `|${span.context().traceId}.${span.context().spanId}.`;
const traceparent = new Traceparent();
traceparent.traceId = spanContext.traceId;
traceparent.spanId = spanContext.spanId;
traceparent.traceFlag = spanContext.traceFlags.toString();
traceparent.parentId = span.parentSpanId ? `|${spanContext.traceId}.${span.parentSpanId}.` : null;
const properties = {
...span.attributes,
};
if (span.status.message) {
properties["status.message"] = span.status.message;
}
AsyncScopeManager.with(span, () => {
clients.forEach((client) => {
if (span.kind === 1) {
// Server
client.trackRequest({
id: id,
name: span.name,
duration: duration,
resultCode: span.status.code,
success: span.status.code === 0,
url: span.attributes.component,
properties: properties,
} as Contracts.RequestTelemetry & Contracts.Identified);
} else {
// Client
client.trackDependency({
id: id,
name: span.name,
duration: duration,
data: span.attributes.component || span.name,
dependencyTypeName: span.attributes.component || span.name,
resultCode: span.status.code,
success: span.status.code === 0,
properties: properties
} as Contracts.DependencyTelemetry & Contracts.Identified);
}
});
});
};
export function enable(enabled: boolean, client: TelemetryClient) {
if (enabled) {
if (clients.length === 0) {
channel.subscribe<any>("azure-coretracing", subscriber);
};
clients.push(client);
} else {
clients = clients.filter((c) => c != client);
if (clients.length === 0) {
channel.unsubscribe("azure-coretracing", subscriber);
}
}
}