@redthreadlabs/tracelog 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +26 -0
- package/README.md +126 -0
- package/index.d.ts +464 -0
- package/index.js +11 -0
- package/lib/InflightEventSet.js +53 -0
- package/lib/activation-method.js +97 -0
- package/lib/agent.js +1226 -0
- package/lib/apm-client/apm-client.js +107 -0
- package/lib/apm-client/channel-writer.js +334 -0
- package/lib/apm-client/jsonl-file-client.js +241 -0
- package/lib/apm-client/ndjson.js +20 -0
- package/lib/apm-client/noop-apm-client.js +79 -0
- package/lib/apm-client/s3-uploader.js +308 -0
- package/lib/apm-client/truncate.js +507 -0
- package/lib/async-hooks-polyfill.js +58 -0
- package/lib/cloud-metadata/aws.js +175 -0
- package/lib/cloud-metadata/azure.js +123 -0
- package/lib/cloud-metadata/callback-coordination.js +159 -0
- package/lib/cloud-metadata/gcp.js +133 -0
- package/lib/cloud-metadata/index.js +175 -0
- package/lib/config/config.js +431 -0
- package/lib/config/normalizers.js +649 -0
- package/lib/config/schema.js +946 -0
- package/lib/constants.js +35 -0
- package/lib/errors.js +303 -0
- package/lib/filters/sanitize-field-names.js +69 -0
- package/lib/http-request.js +249 -0
- package/lib/instrumentation/context.js +56 -0
- package/lib/instrumentation/dropped-spans-stats.js +112 -0
- package/lib/instrumentation/elasticsearch-shared.js +63 -0
- package/lib/instrumentation/express-utils.js +91 -0
- package/lib/instrumentation/generic-span.js +322 -0
- package/lib/instrumentation/http-shared.js +424 -0
- package/lib/instrumentation/ids.js +39 -0
- package/lib/instrumentation/index.js +1078 -0
- package/lib/instrumentation/modules/@apollo/server.js +39 -0
- package/lib/instrumentation/modules/@aws-sdk/client-dynamodb.js +143 -0
- package/lib/instrumentation/modules/@aws-sdk/client-s3.js +230 -0
- package/lib/instrumentation/modules/@aws-sdk/client-sns.js +197 -0
- package/lib/instrumentation/modules/@aws-sdk/client-sqs.js +336 -0
- package/lib/instrumentation/modules/@elastic/elasticsearch.js +343 -0
- package/lib/instrumentation/modules/@hapi/hapi.js +221 -0
- package/lib/instrumentation/modules/@redis/client/dist/lib/client/commands-queue.js +178 -0
- package/lib/instrumentation/modules/@redis/client/dist/lib/client/index.js +49 -0
- package/lib/instrumentation/modules/@smithy/smithy-client.js +198 -0
- package/lib/instrumentation/modules/apollo-server-core.js +49 -0
- package/lib/instrumentation/modules/aws-sdk/dynamodb.js +155 -0
- package/lib/instrumentation/modules/aws-sdk/s3.js +184 -0
- package/lib/instrumentation/modules/aws-sdk/sns.js +232 -0
- package/lib/instrumentation/modules/aws-sdk/sqs.js +361 -0
- package/lib/instrumentation/modules/aws-sdk.js +76 -0
- package/lib/instrumentation/modules/bluebird.js +93 -0
- package/lib/instrumentation/modules/cassandra-driver.js +280 -0
- package/lib/instrumentation/modules/elasticsearch.js +200 -0
- package/lib/instrumentation/modules/express-graphql.js +66 -0
- package/lib/instrumentation/modules/express-queue.js +28 -0
- package/lib/instrumentation/modules/express.js +162 -0
- package/lib/instrumentation/modules/fastify.js +179 -0
- package/lib/instrumentation/modules/finalhandler.js +41 -0
- package/lib/instrumentation/modules/generic-pool.js +85 -0
- package/lib/instrumentation/modules/graphql.js +256 -0
- package/lib/instrumentation/modules/handlebars.js +33 -0
- package/lib/instrumentation/modules/http.js +112 -0
- package/lib/instrumentation/modules/http2.js +320 -0
- package/lib/instrumentation/modules/https.js +68 -0
- package/lib/instrumentation/modules/ioredis.js +94 -0
- package/lib/instrumentation/modules/jade.js +29 -0
- package/lib/instrumentation/modules/kafkajs.js +476 -0
- package/lib/instrumentation/modules/knex.js +91 -0
- package/lib/instrumentation/modules/koa-router.js +74 -0
- package/lib/instrumentation/modules/koa.js +15 -0
- package/lib/instrumentation/modules/memcached.js +100 -0
- package/lib/instrumentation/modules/mimic-response.js +45 -0
- package/lib/instrumentation/modules/mongodb/lib/cmap/connection_pool.js +40 -0
- package/lib/instrumentation/modules/mongodb-core.js +206 -0
- package/lib/instrumentation/modules/mongodb.js +259 -0
- package/lib/instrumentation/modules/mysql.js +200 -0
- package/lib/instrumentation/modules/mysql2.js +140 -0
- package/lib/instrumentation/modules/pg.js +148 -0
- package/lib/instrumentation/modules/pug.js +29 -0
- package/lib/instrumentation/modules/redis.js +176 -0
- package/lib/instrumentation/modules/restify.js +52 -0
- package/lib/instrumentation/modules/tedious.js +159 -0
- package/lib/instrumentation/modules/undici.js +270 -0
- package/lib/instrumentation/modules/ws.js +59 -0
- package/lib/instrumentation/noop-transaction.js +81 -0
- package/lib/instrumentation/run-context/AbstractRunContextManager.js +215 -0
- package/lib/instrumentation/run-context/AsyncHooksRunContextManager.js +106 -0
- package/lib/instrumentation/run-context/AsyncLocalStorageRunContextManager.js +73 -0
- package/lib/instrumentation/run-context/BasicRunContextManager.js +82 -0
- package/lib/instrumentation/run-context/RunContext.js +151 -0
- package/lib/instrumentation/run-context/index.js +23 -0
- package/lib/instrumentation/shimmer.js +123 -0
- package/lib/instrumentation/span-compression.js +239 -0
- package/lib/instrumentation/span.js +621 -0
- package/lib/instrumentation/template-shared.js +43 -0
- package/lib/instrumentation/timer.js +84 -0
- package/lib/instrumentation/transaction.js +571 -0
- package/lib/load-source-map.js +100 -0
- package/lib/logging.js +212 -0
- package/lib/metrics/index.js +92 -0
- package/lib/metrics/platforms/generic/index.js +40 -0
- package/lib/metrics/platforms/generic/process-cpu.js +22 -0
- package/lib/metrics/platforms/generic/process-top.js +157 -0
- package/lib/metrics/platforms/generic/stats.js +34 -0
- package/lib/metrics/platforms/generic/system-cpu.js +51 -0
- package/lib/metrics/platforms/linux/index.js +19 -0
- package/lib/metrics/platforms/linux/stats.js +213 -0
- package/lib/metrics/queue.js +90 -0
- package/lib/metrics/registry.js +52 -0
- package/lib/metrics/reporter.js +119 -0
- package/lib/metrics/runtime.js +77 -0
- package/lib/middleware/connect.js +16 -0
- package/lib/parsers.js +225 -0
- package/lib/propwrap.js +147 -0
- package/lib/stacktraces.js +537 -0
- package/lib/symbols.js +15 -0
- package/lib/tracecontext/index.js +115 -0
- package/lib/tracecontext/traceparent.js +185 -0
- package/lib/tracecontext/tracestate.js +388 -0
- package/lib/wildcard-matcher.js +52 -0
- package/loader.mjs +7 -0
- package/package.json +98 -0
- package/start.d.ts +8 -0
- package/start.js +29 -0
- package/types/aws-lambda.d.ts +98 -0
- package/types/connect.d.ts +23 -0
package/lib/agent.js
ADDED
|
@@ -0,0 +1,1226 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright Shaxpir Inc. and Elasticsearch B.V. and other contributors where applicable.
|
|
3
|
+
* Licensed under the BSD 2-Clause License; you may not use this file except in
|
|
4
|
+
* compliance with the BSD 2-Clause License.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
'use strict';
|
|
8
|
+
|
|
9
|
+
const http = require('http');
|
|
10
|
+
const path = require('path');
|
|
11
|
+
|
|
12
|
+
const isError = require('core-util-is').isError;
|
|
13
|
+
const Filters = require('object-filter-sequence');
|
|
14
|
+
|
|
15
|
+
const { agentActivationMethodFromStartStack } = require('./activation-method');
|
|
16
|
+
const {
|
|
17
|
+
CAPTURE_ERROR_LOG_STACK_TRACES_ALWAYS,
|
|
18
|
+
CAPTURE_ERROR_LOG_STACK_TRACES_MESSAGES,
|
|
19
|
+
} = require('./constants');
|
|
20
|
+
const config = require('./config/config');
|
|
21
|
+
const connect = require('./middleware/connect');
|
|
22
|
+
const constants = require('./constants');
|
|
23
|
+
const errors = require('./errors');
|
|
24
|
+
const { InflightEventSet } = require('./InflightEventSet');
|
|
25
|
+
const { Instrumentation } = require('./instrumentation');
|
|
26
|
+
const logging = require('./logging');
|
|
27
|
+
const Metrics = require('./metrics');
|
|
28
|
+
const parsers = require('./parsers');
|
|
29
|
+
const symbols = require('./symbols');
|
|
30
|
+
const { frameCacheStats, initStackTraceCollection } = require('./stacktraces');
|
|
31
|
+
const Span = require('./instrumentation/span');
|
|
32
|
+
const Transaction = require('./instrumentation/transaction');
|
|
33
|
+
const { createApmClient } = require('./apm-client/apm-client');
|
|
34
|
+
|
|
35
|
+
const IncomingMessage = http.IncomingMessage;
|
|
36
|
+
const ServerResponse = http.ServerResponse;
|
|
37
|
+
|
|
38
|
+
const version = require('../package').version;
|
|
39
|
+
|
|
40
|
+
// ---- Agent
|
|
41
|
+
|
|
42
|
+
module.exports = Agent;
|
|
43
|
+
|
|
44
|
+
function Agent() {
|
|
45
|
+
// Early configuration to ensure `agent.logger` works before `agent.start()`.
|
|
46
|
+
this.logger = config.configLogger();
|
|
47
|
+
|
|
48
|
+
// Get an initial pre-.start() configuration of agent defaults. This is a
|
|
49
|
+
// crutch for Agent APIs that depend on `agent._conf`.
|
|
50
|
+
this._conf = config.initialConfig(this.logger);
|
|
51
|
+
|
|
52
|
+
this._httpClient = null;
|
|
53
|
+
this._uncaughtExceptionListener = null;
|
|
54
|
+
this._inflightEvents = new InflightEventSet();
|
|
55
|
+
this._instrumentation = new Instrumentation(this);
|
|
56
|
+
this._metrics = new Metrics(this);
|
|
57
|
+
this._errorFilters = new Filters();
|
|
58
|
+
this._transactionFilters = new Filters();
|
|
59
|
+
this._spanFilters = new Filters();
|
|
60
|
+
this._eventFilters = new Filters();
|
|
61
|
+
this._apmClient = null;
|
|
62
|
+
|
|
63
|
+
this.middleware = { connect: connect.bind(this) };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
Object.defineProperty(Agent.prototype, 'currentTransaction', {
|
|
67
|
+
get() {
|
|
68
|
+
return this._instrumentation.currTransaction();
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
Object.defineProperty(Agent.prototype, 'currentSpan', {
|
|
73
|
+
get() {
|
|
74
|
+
return this._instrumentation.currSpan();
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
Object.defineProperty(Agent.prototype, 'currentTraceparent', {
|
|
79
|
+
get() {
|
|
80
|
+
const current =
|
|
81
|
+
this._instrumentation.currSpan() ||
|
|
82
|
+
this._instrumentation.currTransaction();
|
|
83
|
+
return current ? current.traceparent : null;
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
Object.defineProperty(Agent.prototype, 'currentTraceIds', {
|
|
88
|
+
get() {
|
|
89
|
+
return this._instrumentation.ids();
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
// Destroy this agent. This prevents any new agent processing, communication
|
|
94
|
+
// with APM server, and resets changed global state *as much as is possible*.
|
|
95
|
+
//
|
|
96
|
+
// In the typical uses case -- a singleton Agent running for the full process
|
|
97
|
+
// lifetime -- it is *not* necessary to call `agent.destroy()`. It is used
|
|
98
|
+
// for some testing.
|
|
99
|
+
//
|
|
100
|
+
// Limitations:
|
|
101
|
+
// - Patching/wrapping of functions for instrumentation *is* undone, but
|
|
102
|
+
// references to the wrapped versions can remain.
|
|
103
|
+
// - There may be in-flight tasks (in ins.addEndedSpan() and
|
|
104
|
+
// agent.captureError() for example) that will complete after this destroy
|
|
105
|
+
// completes. They should have no impact other than CPU/resource use.
|
|
106
|
+
Agent.prototype.destroy = async function () {
|
|
107
|
+
if (this._apmClient && this._apmClient.destroy) {
|
|
108
|
+
this._apmClient.destroy();
|
|
109
|
+
}
|
|
110
|
+
// So in-flight tasks in ins.addEndedSpan() and agent.captureError() do
|
|
111
|
+
// not use the destroyed transport.
|
|
112
|
+
this._apmClient = null;
|
|
113
|
+
|
|
114
|
+
// So in-flight tasks do not call user-added filters after the agent has
|
|
115
|
+
// been destroyed.
|
|
116
|
+
this._errorFilters = new Filters();
|
|
117
|
+
this._transactionFilters = new Filters();
|
|
118
|
+
this._spanFilters = new Filters();
|
|
119
|
+
this._eventFilters = new Filters();
|
|
120
|
+
|
|
121
|
+
if (this._uncaughtExceptionListener) {
|
|
122
|
+
process.removeListener(
|
|
123
|
+
'uncaughtException',
|
|
124
|
+
this._uncaughtExceptionListener,
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
this._metrics.stop();
|
|
128
|
+
this._instrumentation.stop();
|
|
129
|
+
|
|
130
|
+
// Allow a new Agent instance to `.start()`. Typically this is only relevant
|
|
131
|
+
// for tests that may use multiple Agent instances in a single test process.
|
|
132
|
+
global[symbols.agentInitialized] = null;
|
|
133
|
+
|
|
134
|
+
if (
|
|
135
|
+
this._origStackTraceLimit &&
|
|
136
|
+
Error.stackTraceLimit !== this._origStackTraceLimit
|
|
137
|
+
) {
|
|
138
|
+
Error.stackTraceLimit = this._origStackTraceLimit;
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
// These are metrics about the agent itself -- separate from the metrics
|
|
143
|
+
// gathered on behalf of the using app and sent to APM server. Currently these
|
|
144
|
+
// are only useful for internal debugging of the APM agent itself.
|
|
145
|
+
//
|
|
146
|
+
// **These stats are NOT a promised interface.**
|
|
147
|
+
Agent.prototype._getStats = function () {
|
|
148
|
+
const stats = {
|
|
149
|
+
frameCache: frameCacheStats,
|
|
150
|
+
};
|
|
151
|
+
if (
|
|
152
|
+
this._instrumentation._runCtxMgr &&
|
|
153
|
+
this._instrumentation._runCtxMgr._runContextFromAsyncId
|
|
154
|
+
) {
|
|
155
|
+
stats.runContextFromAsyncIdSize =
|
|
156
|
+
this._instrumentation._runCtxMgr._runContextFromAsyncId.size;
|
|
157
|
+
}
|
|
158
|
+
if (this._apmClient && typeof this._apmClient._getStats === 'function') {
|
|
159
|
+
stats.apmclient = this._apmClient._getStats();
|
|
160
|
+
}
|
|
161
|
+
return stats;
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
Agent.prototype.addPatch = function (modules, handler) {
|
|
165
|
+
return this._instrumentation.addPatch.apply(this._instrumentation, arguments);
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
Agent.prototype.removePatch = function (modules, handler) {
|
|
169
|
+
return this._instrumentation.removePatch.apply(
|
|
170
|
+
this._instrumentation,
|
|
171
|
+
arguments,
|
|
172
|
+
);
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
Agent.prototype.clearPatches = function (modules) {
|
|
176
|
+
return this._instrumentation.clearPatches.apply(
|
|
177
|
+
this._instrumentation,
|
|
178
|
+
arguments,
|
|
179
|
+
);
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
Agent.prototype.startTransaction = function (
|
|
183
|
+
name,
|
|
184
|
+
type,
|
|
185
|
+
{ startTime, childOf } = {},
|
|
186
|
+
) {
|
|
187
|
+
return this._instrumentation.startTransaction.apply(
|
|
188
|
+
this._instrumentation,
|
|
189
|
+
arguments,
|
|
190
|
+
);
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
Agent.prototype.endTransaction = function (result, endTime) {
|
|
194
|
+
return this._instrumentation.endTransaction.apply(
|
|
195
|
+
this._instrumentation,
|
|
196
|
+
arguments,
|
|
197
|
+
);
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
Agent.prototype.setTransactionName = function (name) {
|
|
201
|
+
return this._instrumentation.setTransactionName.apply(
|
|
202
|
+
this._instrumentation,
|
|
203
|
+
arguments,
|
|
204
|
+
);
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Sets outcome value for current transaction
|
|
209
|
+
*
|
|
210
|
+
* The setOutcome method allows users to override the default
|
|
211
|
+
* outcome handling in the agent and set their own value.
|
|
212
|
+
*
|
|
213
|
+
* @param {string} outcome must be one of `failure`, `success`, or `unknown`
|
|
214
|
+
*/
|
|
215
|
+
Agent.prototype.setTransactionOutcome = function (outcome) {
|
|
216
|
+
return this._instrumentation.setTransactionOutcome.apply(
|
|
217
|
+
this._instrumentation,
|
|
218
|
+
arguments,
|
|
219
|
+
);
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
Agent.prototype.startSpan = function (
|
|
223
|
+
name,
|
|
224
|
+
type,
|
|
225
|
+
subtype,
|
|
226
|
+
action,
|
|
227
|
+
{ startTime, childOf, exitSpan } = {},
|
|
228
|
+
) {
|
|
229
|
+
return this._instrumentation.startSpan.apply(
|
|
230
|
+
this._instrumentation,
|
|
231
|
+
arguments,
|
|
232
|
+
);
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Sets outcome value for current active span
|
|
237
|
+
*
|
|
238
|
+
* The setOutcome method allows users to override the default
|
|
239
|
+
* outcome handling in the agent and set their own value.
|
|
240
|
+
*
|
|
241
|
+
* @param {string} outcome must be one of `failure`, `success`, or `unknown`
|
|
242
|
+
*/
|
|
243
|
+
Agent.prototype.setSpanOutcome = function (outcome) {
|
|
244
|
+
return this._instrumentation.setSpanOutcome.apply(
|
|
245
|
+
this._instrumentation,
|
|
246
|
+
arguments,
|
|
247
|
+
);
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
Agent.prototype._config = function (opts) {
|
|
251
|
+
this._conf = config.createConfig(opts, this.logger);
|
|
252
|
+
this.logger = this._conf.logger;
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
Agent.prototype.isStarted = function () {
|
|
256
|
+
return global[symbols.agentInitialized];
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
Agent.prototype.start = function (opts) {
|
|
260
|
+
if (this.isStarted()) {
|
|
261
|
+
throw new Error('Do not call .start() more than once');
|
|
262
|
+
}
|
|
263
|
+
global[symbols.agentInitialized] = true;
|
|
264
|
+
|
|
265
|
+
this._config(opts);
|
|
266
|
+
|
|
267
|
+
if (!this._conf.active) {
|
|
268
|
+
this.logger.debug('Tracelog agent disabled (`active` is false)');
|
|
269
|
+
return this;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// Log preamble showing agent, environment and config relevant info
|
|
273
|
+
const preambleData = this._conf.loggingPreambleData;
|
|
274
|
+
const isPreviewVersion = version.indexOf('-') !== -1;
|
|
275
|
+
const startStack = {};
|
|
276
|
+
|
|
277
|
+
if (this._conf.active && this._conf.serviceName) {
|
|
278
|
+
this._origStackTraceLimit = Error.stackTraceLimit;
|
|
279
|
+
Error.stackTraceLimit = 20; // require more than default 10 for `agentActivationMethodFromStartStack()`
|
|
280
|
+
Error.captureStackTrace(startStack);
|
|
281
|
+
Error.stackTraceLimit = this._origStackTraceLimit;
|
|
282
|
+
this._agentActivationMethod = agentActivationMethodFromStartStack(
|
|
283
|
+
startStack,
|
|
284
|
+
this.logger,
|
|
285
|
+
);
|
|
286
|
+
preambleData.activationMethod = this._agentActivationMethod;
|
|
287
|
+
|
|
288
|
+
if (this._conf.logLevel === 'trace') {
|
|
289
|
+
// Attempt to load package.json from process.argv.
|
|
290
|
+
let pkg = null;
|
|
291
|
+
try {
|
|
292
|
+
var basedir = path.dirname(process.argv[1] || '.');
|
|
293
|
+
pkg = require(path.join(basedir, 'package.json'));
|
|
294
|
+
} catch (e) {}
|
|
295
|
+
|
|
296
|
+
// Add stack & dependencies for extra information
|
|
297
|
+
preambleData.dependencies = pkg
|
|
298
|
+
? pkg.dependencies
|
|
299
|
+
: '<could not determine>';
|
|
300
|
+
preambleData.startTrace = startStack.stack.split(/\n */).slice(1);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
this.logger.info(preambleData, 'Tracelog v%s', version);
|
|
305
|
+
|
|
306
|
+
if (!logging.isLoggerCustom(this.logger)) {
|
|
307
|
+
// Periodically dump the current config (delta from defaults) when logging
|
|
308
|
+
// at "trace"-level. This allows getting the effective config from a running
|
|
309
|
+
// agent by setting trace-level logging and getting 1 minute of logs.
|
|
310
|
+
// (Sometimes getting logs from application *start* is no possible.)
|
|
311
|
+
setInterval(() => {
|
|
312
|
+
if (this.logger.isLevelEnabled('trace')) {
|
|
313
|
+
try {
|
|
314
|
+
const currConfig = this._conf.getCurrConfig();
|
|
315
|
+
this.logger.trace({ currConfig }, 'currConfig');
|
|
316
|
+
} catch (err) {
|
|
317
|
+
this.logger.trace({ err }, 'error calculating currConfig');
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}, 60 * 1000).unref();
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
if (isPreviewVersion) {
|
|
324
|
+
this.logger.warn(
|
|
325
|
+
'Version %s is a pre-release and not intended for use in production environments',
|
|
326
|
+
version,
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
if (!this._conf.serviceName) {
|
|
331
|
+
this.logger.error(
|
|
332
|
+
'Tracelog is incorrectly configured: Missing serviceName (tracing will be disabled)',
|
|
333
|
+
);
|
|
334
|
+
this._conf.active = false;
|
|
335
|
+
return this;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
initStackTraceCollection();
|
|
339
|
+
this._apmClient = createApmClient(this._conf, this);
|
|
340
|
+
|
|
341
|
+
this._instrumentation.start();
|
|
342
|
+
|
|
343
|
+
if (this._isMetricsEnabled()) {
|
|
344
|
+
this._metrics.start();
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
Error.stackTraceLimit = this._conf.stackTraceLimit;
|
|
348
|
+
if (this._conf.captureExceptions) this.handleUncaughtExceptions();
|
|
349
|
+
|
|
350
|
+
return this;
|
|
351
|
+
};
|
|
352
|
+
|
|
353
|
+
Agent.prototype._isMetricsEnabled = function () {
|
|
354
|
+
return this._conf.metricsInterval !== 0 && !this._conf.contextPropagationOnly;
|
|
355
|
+
};
|
|
356
|
+
|
|
357
|
+
Agent.prototype.getServiceName = function () {
|
|
358
|
+
return this._conf ? this._conf.serviceName : undefined;
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
Agent.prototype.getServiceVersion = function () {
|
|
362
|
+
return this._conf ? this._conf.serviceVersion : undefined;
|
|
363
|
+
};
|
|
364
|
+
|
|
365
|
+
Agent.prototype.getServiceEnvironment = function () {
|
|
366
|
+
return this._conf ? this._conf.environment : undefined;
|
|
367
|
+
};
|
|
368
|
+
|
|
369
|
+
Agent.prototype.getServiceNodeName = function () {
|
|
370
|
+
return this._conf ? this._conf.serviceNodeName : undefined;
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
Agent.prototype.setFramework = function ({ name, version, overwrite = true }) {
|
|
374
|
+
if (!this._apmClient || !this._conf) {
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
const conf = {};
|
|
378
|
+
if (name && (overwrite || !this._conf.frameworkName))
|
|
379
|
+
this._conf.frameworkName = conf.frameworkName = name;
|
|
380
|
+
if (version && (overwrite || !this._conf.frameworkVersion))
|
|
381
|
+
this._conf.frameworkVersion = conf.frameworkVersion = version;
|
|
382
|
+
this._apmClient.config(conf);
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
Agent.prototype.setUserContext = function (context) {
|
|
386
|
+
var trans = this._instrumentation.currTransaction();
|
|
387
|
+
if (!trans) return false;
|
|
388
|
+
trans.setUserContext(context);
|
|
389
|
+
return true;
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
Agent.prototype.setCustomContext = function (context) {
|
|
393
|
+
var trans = this._instrumentation.currTransaction();
|
|
394
|
+
if (!trans) return false;
|
|
395
|
+
trans.setCustomContext(context);
|
|
396
|
+
return true;
|
|
397
|
+
};
|
|
398
|
+
|
|
399
|
+
Agent.prototype.setGlobalLabel = function (key, value) {
|
|
400
|
+
if (!this._conf.globalLabels) this._conf.globalLabels = [];
|
|
401
|
+
const foundPos = this._conf.globalLabels.findIndex(([name]) => key === name);
|
|
402
|
+
if (foundPos > -1) {
|
|
403
|
+
this._conf.globalLabels[foundPos][1] = value;
|
|
404
|
+
} else {
|
|
405
|
+
this._conf.globalLabels.push([key, value]);
|
|
406
|
+
}
|
|
407
|
+
if (!this._apmClient) {
|
|
408
|
+
this.logger.warn('cannot setGlobalLabel on inactive or unconfigured agent');
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
this._apmClient.config({
|
|
412
|
+
globalLabels: this._conf.globalLabels.reduce((acc, [k, v]) => {
|
|
413
|
+
acc[k] = v;
|
|
414
|
+
return acc;
|
|
415
|
+
}, {}),
|
|
416
|
+
});
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
Agent.prototype.setLabel = function (key, value, stringify) {
|
|
420
|
+
var trans = this._instrumentation.currTransaction();
|
|
421
|
+
if (!trans) return false;
|
|
422
|
+
return trans.setLabel(key, value, stringify);
|
|
423
|
+
};
|
|
424
|
+
|
|
425
|
+
Agent.prototype.addLabels = function (labels, stringify) {
|
|
426
|
+
var trans = this._instrumentation.currTransaction();
|
|
427
|
+
if (!trans) return false;
|
|
428
|
+
return trans.addLabels(labels, stringify);
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
Agent.prototype.addFilter = function (fn) {
|
|
432
|
+
this.addErrorFilter(fn);
|
|
433
|
+
this.addTransactionFilter(fn);
|
|
434
|
+
this.addSpanFilter(fn);
|
|
435
|
+
this.addEventFilter(fn);
|
|
436
|
+
// Note: This does *not* add to *metadata* filters, partly for backward
|
|
437
|
+
// compat -- the structure of metadata objects is quite different and could
|
|
438
|
+
// break existing filters -- and partly because that different structure
|
|
439
|
+
// means it makes less sense to re-use the same function to filter them.
|
|
440
|
+
};
|
|
441
|
+
|
|
442
|
+
Agent.prototype.addErrorFilter = function (fn) {
|
|
443
|
+
if (typeof fn !== 'function') {
|
|
444
|
+
this.logger.error("Can't add filter of type %s", typeof fn);
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
this._errorFilters.push(fn);
|
|
449
|
+
};
|
|
450
|
+
|
|
451
|
+
Agent.prototype.addTransactionFilter = function (fn) {
|
|
452
|
+
if (typeof fn !== 'function') {
|
|
453
|
+
this.logger.error("Can't add filter of type %s", typeof fn);
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
this._transactionFilters.push(fn);
|
|
458
|
+
};
|
|
459
|
+
|
|
460
|
+
Agent.prototype.addSpanFilter = function (fn) {
|
|
461
|
+
if (typeof fn !== 'function') {
|
|
462
|
+
this.logger.error("Can't add filter of type %s", typeof fn);
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
this._spanFilters.push(fn);
|
|
467
|
+
};
|
|
468
|
+
|
|
469
|
+
Agent.prototype.addEventFilter = function (fn) {
|
|
470
|
+
if (typeof fn !== 'function') {
|
|
471
|
+
this.logger.error("Can't add filter of type %s", typeof fn);
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
this._eventFilters.push(fn);
|
|
476
|
+
};
|
|
477
|
+
|
|
478
|
+
Agent.prototype.addMetadataFilter = function (fn) {
|
|
479
|
+
if (typeof fn !== 'function') {
|
|
480
|
+
this.logger.error("Can't add filter of type %s", typeof fn);
|
|
481
|
+
return;
|
|
482
|
+
} else if (!this._apmClient) {
|
|
483
|
+
this.logger.error(
|
|
484
|
+
'cannot add metadata filter to inactive or unconfigured agent (agent has no transport)',
|
|
485
|
+
);
|
|
486
|
+
return;
|
|
487
|
+
} else if (typeof this._apmClient.addMetadataFilter !== 'function') {
|
|
488
|
+
// Graceful failure if unexpectedly using a too-old APM client.
|
|
489
|
+
this.logger.error(
|
|
490
|
+
'cannot add metadata filter: transport does not support addMetadataFilter',
|
|
491
|
+
);
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// Metadata filters are handled by the APM client, where metadata is
|
|
496
|
+
// processed.
|
|
497
|
+
this._apmClient.addMetadataFilter(fn);
|
|
498
|
+
};
|
|
499
|
+
|
|
500
|
+
const EMPTY_OPTS = {};
|
|
501
|
+
|
|
502
|
+
// Capture an APM server "error" event for the given `err` and send it to APM
|
|
503
|
+
// server.
|
|
504
|
+
//
|
|
505
|
+
// Usage:
|
|
506
|
+
// captureError(err, opts, cb)
|
|
507
|
+
// captureError(err, opts)
|
|
508
|
+
// captureError(err, cb)
|
|
509
|
+
//
|
|
510
|
+
// where:
|
|
511
|
+
// - `err` is an Error instance, or a string message, or a "parameterized string
|
|
512
|
+
// message" object, e.g.:
|
|
513
|
+
// {
|
|
514
|
+
// message: "this is my message template: %d %s"},
|
|
515
|
+
// params: [ 42, "another param" ]
|
|
516
|
+
// }
|
|
517
|
+
// - `opts` can include any of the following (all optional):
|
|
518
|
+
// - `opts.timestamp` - Milliseconds since the Unix epoch. Defaults to now.
|
|
519
|
+
// - `opts.user` - Object to add to `error.context.user`.
|
|
520
|
+
// - `opts.tags` - Deprecated, use `opts.labels`. Object to add to
|
|
521
|
+
// `error.context.labels`.
|
|
522
|
+
// - `opts.labels` - Object to add to `error.context.labels`.
|
|
523
|
+
// - `opts.custom` - Object to add to `error.context.custom`.
|
|
524
|
+
// - `opts.message` - If `err` is an Error instance, this string is added to
|
|
525
|
+
// `error.log.message` (unless it matches err.message).
|
|
526
|
+
// - `opts.request` - HTTP request (node `IncomingMessage` instance) to use
|
|
527
|
+
// for `error.context.request`. If not given, a `req` on the parent
|
|
528
|
+
// transaction (see `opts.parent` below) will be used.
|
|
529
|
+
// - `opts.response` - HTTP response (node `ServerResponse` instance) to use
|
|
530
|
+
// for `error.context.response`. If not given, a `res` on the parent
|
|
531
|
+
// transaction (see `opts.parent` below) will be used.
|
|
532
|
+
// - `opts.handled` - Boolean indicating if this exception was handled by
|
|
533
|
+
// application code. Default true. Setting to `false` also results in the
|
|
534
|
+
// error being flushed to APM server as soon as it is processed.
|
|
535
|
+
// - `opts.captureAttributes` - Boolean. Default true. Set to false to *not*
|
|
536
|
+
// include properties of `err` as attributes on the APM error event.
|
|
537
|
+
// - `opts.skipOutcome` - Boolean. Default false. Set to true to not have
|
|
538
|
+
// this captured error set `<currentSpan>.outcome = failure`.
|
|
539
|
+
// - `opts.parent` - A Transaction or Span instance to make the parent of
|
|
540
|
+
// this error. If not given (undefined), then the current span or
|
|
541
|
+
// transaction will be used. If `null` is given, then no span or transaction
|
|
542
|
+
// will be used.
|
|
543
|
+
// - `opts.exceptionType` - A string to use for `error.exception.type`. By
|
|
544
|
+
// default this is `err.name`. This option is only relevant if `err` is an
|
|
545
|
+
// Error instance.
|
|
546
|
+
// - `cb` is a callback `function (captureErr, apmErrorIdString)`. If provided,
|
|
547
|
+
// the error will be flushed to APM server as soon as it is processed, and
|
|
548
|
+
// `cb` will be called when that send is complete.
|
|
549
|
+
Agent.prototype.writeError = function (err, opts, cb) {
|
|
550
|
+
if (typeof opts === 'function') {
|
|
551
|
+
cb = opts;
|
|
552
|
+
opts = EMPTY_OPTS;
|
|
553
|
+
} else if (!opts) {
|
|
554
|
+
opts = EMPTY_OPTS;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
const id = errors.generateErrorId();
|
|
558
|
+
|
|
559
|
+
if (!this.isStarted()) {
|
|
560
|
+
if (cb) {
|
|
561
|
+
cb(new Error('cannot capture error before agent is started'), id);
|
|
562
|
+
}
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// Avoid unneeded error/stack processing if only propagating trace-context.
|
|
567
|
+
if (this._conf.contextPropagationOnly) {
|
|
568
|
+
if (cb) {
|
|
569
|
+
process.nextTick(cb, null, id);
|
|
570
|
+
}
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
const agent = this;
|
|
575
|
+
let callSiteLoc = null;
|
|
576
|
+
const errIsError = isError(err);
|
|
577
|
+
const handled = opts.handled !== false; // default true
|
|
578
|
+
const shouldCaptureAttributes = opts.captureAttributes !== false; // default true
|
|
579
|
+
const skipOutcome = Boolean(opts.skipOutcome);
|
|
580
|
+
const timestampUs = opts.timestamp
|
|
581
|
+
? Math.floor(opts.timestamp * 1000)
|
|
582
|
+
: Date.now() * 1000;
|
|
583
|
+
|
|
584
|
+
// Determine transaction/span context to associate with this error.
|
|
585
|
+
let parent;
|
|
586
|
+
let span;
|
|
587
|
+
let trans;
|
|
588
|
+
if (opts.parent === undefined) {
|
|
589
|
+
parent =
|
|
590
|
+
this._instrumentation.currSpan() ||
|
|
591
|
+
this._instrumentation.currTransaction();
|
|
592
|
+
} else if (opts.parent === null) {
|
|
593
|
+
parent = null;
|
|
594
|
+
} else {
|
|
595
|
+
parent = opts.parent;
|
|
596
|
+
}
|
|
597
|
+
if (parent instanceof Transaction) {
|
|
598
|
+
span = null;
|
|
599
|
+
trans = parent;
|
|
600
|
+
} else if (parent instanceof Span) {
|
|
601
|
+
span = parent;
|
|
602
|
+
trans = parent.transaction;
|
|
603
|
+
}
|
|
604
|
+
const traceContext = (span || trans || {})._context;
|
|
605
|
+
const req =
|
|
606
|
+
opts.request instanceof IncomingMessage ? opts.request : trans && trans.req;
|
|
607
|
+
const res =
|
|
608
|
+
opts.response instanceof ServerResponse
|
|
609
|
+
? opts.response
|
|
610
|
+
: trans && trans.res;
|
|
611
|
+
|
|
612
|
+
// As an added feature, for *some* cases, we capture a stacktrace at the point
|
|
613
|
+
// this `captureError` was called. This is added to `error.log.stacktrace`.
|
|
614
|
+
if (
|
|
615
|
+
handled &&
|
|
616
|
+
(agent._conf.captureErrorLogStackTraces ===
|
|
617
|
+
CAPTURE_ERROR_LOG_STACK_TRACES_ALWAYS ||
|
|
618
|
+
(!errIsError &&
|
|
619
|
+
agent._conf.captureErrorLogStackTraces ===
|
|
620
|
+
CAPTURE_ERROR_LOG_STACK_TRACES_MESSAGES))
|
|
621
|
+
) {
|
|
622
|
+
callSiteLoc = {};
|
|
623
|
+
Error.captureStackTrace(callSiteLoc, Agent.prototype.writeError);
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
if (span && !skipOutcome) {
|
|
627
|
+
span._setOutcomeFromErrorCapture(constants.OUTCOME_FAILURE);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
// Note this error as an "inflight" event. See Agent#flush().
|
|
631
|
+
const inflightEvents = this._inflightEvents;
|
|
632
|
+
inflightEvents.add(id);
|
|
633
|
+
|
|
634
|
+
// Move the remaining captureError processing to a later tick because:
|
|
635
|
+
// 1. This allows the calling code to continue processing. For example, for
|
|
636
|
+
// Express instrumentation this can significantly improve latency in
|
|
637
|
+
// the app's endpoints because the response does not proceed until the
|
|
638
|
+
// error handlers return.
|
|
639
|
+
// 2. Gathering `error.context.response` in the same tick results in data
|
|
640
|
+
// for a response that hasn't yet completed (no headers, unset status_code,
|
|
641
|
+
// etc.).
|
|
642
|
+
setImmediate(() => {
|
|
643
|
+
// Gather `error.context.*`.
|
|
644
|
+
const errorContext = {
|
|
645
|
+
user: Object.assign(
|
|
646
|
+
{},
|
|
647
|
+
req && parsers.getUserContextFromRequest(req),
|
|
648
|
+
trans && trans._user,
|
|
649
|
+
opts.user,
|
|
650
|
+
),
|
|
651
|
+
tags: Object.assign({}, trans && trans._labels, opts.tags, opts.labels),
|
|
652
|
+
custom: Object.assign({}, trans && trans._custom, opts.custom),
|
|
653
|
+
};
|
|
654
|
+
if (req) {
|
|
655
|
+
errorContext.request = parsers.getContextFromRequest(
|
|
656
|
+
req,
|
|
657
|
+
agent._conf,
|
|
658
|
+
'errors',
|
|
659
|
+
);
|
|
660
|
+
}
|
|
661
|
+
if (res) {
|
|
662
|
+
errorContext.response = parsers.getContextFromResponse(
|
|
663
|
+
res,
|
|
664
|
+
agent._conf,
|
|
665
|
+
true,
|
|
666
|
+
);
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
errors.createAPMError(
|
|
670
|
+
{
|
|
671
|
+
log: agent.logger,
|
|
672
|
+
id,
|
|
673
|
+
exception: errIsError ? err : null,
|
|
674
|
+
logMessage: errIsError ? null : err,
|
|
675
|
+
shouldCaptureAttributes,
|
|
676
|
+
timestampUs,
|
|
677
|
+
handled,
|
|
678
|
+
callSiteLoc,
|
|
679
|
+
message: opts.message,
|
|
680
|
+
sourceLinesAppFrames: agent._conf.sourceLinesErrorAppFrames,
|
|
681
|
+
sourceLinesLibraryFrames: agent._conf.sourceLinesErrorLibraryFrames,
|
|
682
|
+
trans,
|
|
683
|
+
traceContext,
|
|
684
|
+
errorContext,
|
|
685
|
+
exceptionType: opts.exceptionType,
|
|
686
|
+
},
|
|
687
|
+
function filterAndSendError(_err, apmError) {
|
|
688
|
+
// _err is always null from createAPMError.
|
|
689
|
+
|
|
690
|
+
apmError = agent._errorFilters.process(apmError);
|
|
691
|
+
if (!apmError) {
|
|
692
|
+
agent.logger.debug('error ignored by filter %o', { id });
|
|
693
|
+
inflightEvents.delete(id);
|
|
694
|
+
if (cb) {
|
|
695
|
+
cb(null, id);
|
|
696
|
+
}
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
if (agent._apmClient) {
|
|
701
|
+
agent.logger.debug('Sending error to tracelog: %o', { id });
|
|
702
|
+
agent._apmClient.sendError(apmError);
|
|
703
|
+
inflightEvents.delete(id);
|
|
704
|
+
if (!handled || cb) {
|
|
705
|
+
// Immediately flush *unhandled* errors -- those from
|
|
706
|
+
// `uncaughtException` -- on the assumption that the process may
|
|
707
|
+
// soon crash. Also flush when a `cb` is provided.
|
|
708
|
+
agent.flush(function (flushErr) {
|
|
709
|
+
if (cb) {
|
|
710
|
+
cb(flushErr, id);
|
|
711
|
+
}
|
|
712
|
+
});
|
|
713
|
+
}
|
|
714
|
+
} else {
|
|
715
|
+
inflightEvents.delete(id);
|
|
716
|
+
if (cb) {
|
|
717
|
+
cb(new Error('cannot send error: missing transport'), id);
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
},
|
|
721
|
+
);
|
|
722
|
+
});
|
|
723
|
+
};
|
|
724
|
+
|
|
725
|
+
// Capture an arbitrary custom event.
|
|
726
|
+
//
|
|
727
|
+
// Usage:
|
|
728
|
+
// captureEvent(type, opts)
|
|
729
|
+
// captureEvent(type, opts, cb)
|
|
730
|
+
//
|
|
731
|
+
// - `type` {string} - Event type/category (e.g. 'page_view', 'purchase').
|
|
732
|
+
// - `opts` {Object} - Event data:
|
|
733
|
+
// - `message` {string} - Human-readable description.
|
|
734
|
+
// - `level` {string} - Severity: 'debug', 'info', 'warn', 'error', 'fatal'.
|
|
735
|
+
// - `timestamp` {number} - Unix epoch ms. Defaults to Date.now().
|
|
736
|
+
// - `duration` {number} - Duration in ms.
|
|
737
|
+
// - `error` {Error|any} - Error object. Safely extracts message, type, code,
|
|
738
|
+
// and stack trace into the event record, and also emits a full error record
|
|
739
|
+
// via captureError.
|
|
740
|
+
// - `user` {Object} - End-user identity: { id, email, username }.
|
|
741
|
+
// - `client` {Object} - Client environment: { name, version, os, device, runtime }.
|
|
742
|
+
// - `params` {Object} - Arbitrary key-value data.
|
|
743
|
+
// - `cb` {Function} - Optional callback, called after the event is buffered.
|
|
744
|
+
Agent.prototype.writeEvent = function (type, opts, cb) {
|
|
745
|
+
if (typeof opts === 'function') {
|
|
746
|
+
cb = opts;
|
|
747
|
+
opts = {};
|
|
748
|
+
} else if (!opts) {
|
|
749
|
+
opts = {};
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
if (!this.isStarted()) {
|
|
753
|
+
if (cb) {
|
|
754
|
+
cb(new Error('cannot write event before agent is started'));
|
|
755
|
+
}
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
if (this._conf.contextPropagationOnly) {
|
|
760
|
+
if (cb) {
|
|
761
|
+
process.nextTick(cb);
|
|
762
|
+
}
|
|
763
|
+
return;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
if (this._apmClient) {
|
|
767
|
+
const event = this._eventFilters.process(_buildEvent(type, opts));
|
|
768
|
+
if (event) {
|
|
769
|
+
this._apmClient.sendEvent(event);
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
// If an error was provided, also emit a full error record
|
|
774
|
+
if (opts.error != null) {
|
|
775
|
+
this.writeError(opts.error);
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
if (cb) {
|
|
779
|
+
process.nextTick(cb);
|
|
780
|
+
}
|
|
781
|
+
};
|
|
782
|
+
|
|
783
|
+
// Capture a batch of custom events at once. Designed for server endpoints
|
|
784
|
+
// that receive batches of events from client devices (mobile apps, browsers).
|
|
785
|
+
//
|
|
786
|
+
// Usage:
|
|
787
|
+
// captureEvents(events)
|
|
788
|
+
// captureEvents(events, cb)
|
|
789
|
+
//
|
|
790
|
+
// - `events` {Array<Object>} - Each element must have a `type` and may include
|
|
791
|
+
// the same fields as `captureEvent` opts: message, level, timestamp, duration,
|
|
792
|
+
// user, client, params.
|
|
793
|
+
// - `cb` {Function} - Optional callback, called after all events are buffered.
|
|
794
|
+
Agent.prototype.writeEvents = function (events, cb) {
|
|
795
|
+
if (!Array.isArray(events) || events.length === 0) {
|
|
796
|
+
if (cb) process.nextTick(cb);
|
|
797
|
+
return;
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
if (!this.isStarted()) {
|
|
801
|
+
if (cb) {
|
|
802
|
+
cb(new Error('cannot write events before agent is started'));
|
|
803
|
+
}
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
if (this._conf.contextPropagationOnly) {
|
|
808
|
+
if (cb) {
|
|
809
|
+
process.nextTick(cb);
|
|
810
|
+
}
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
if (this._apmClient) {
|
|
815
|
+
for (const item of events) {
|
|
816
|
+
const event = this._eventFilters.process(_buildEvent(item.type, item));
|
|
817
|
+
if (event) {
|
|
818
|
+
this._apmClient.sendEvent(event);
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
if (cb) {
|
|
824
|
+
process.nextTick(cb);
|
|
825
|
+
}
|
|
826
|
+
};
|
|
827
|
+
|
|
828
|
+
// --- Channels ---
|
|
829
|
+
//
|
|
830
|
+
// A Channel routes records to a named JSONL file. The agent itself is
|
|
831
|
+
// the default channel ('server'). Named channels are created lazily via
|
|
832
|
+
// getChannel(name) and write to separate files (e.g. tracelog-client-*.jsonl).
|
|
833
|
+
|
|
834
|
+
/**
|
|
835
|
+
* Get a named channel. Returns an object with writeEvent, writeEvents,
|
|
836
|
+
* writeError, writeTransaction, and writeSpan methods that route to the
|
|
837
|
+
* named channel's JSONL file.
|
|
838
|
+
*/
|
|
839
|
+
Agent.prototype.getChannel = function (name) {
|
|
840
|
+
if (!name || typeof name !== 'string') {
|
|
841
|
+
throw new Error('Channel name must be a non-empty string');
|
|
842
|
+
}
|
|
843
|
+
return new Channel(this, name);
|
|
844
|
+
};
|
|
845
|
+
|
|
846
|
+
function Channel(agent, name) {
|
|
847
|
+
this._agent = agent;
|
|
848
|
+
this._name = name;
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
Channel.prototype.writeEvent = function (type, opts, cb) {
|
|
852
|
+
if (typeof opts === 'function') {
|
|
853
|
+
cb = opts;
|
|
854
|
+
opts = {};
|
|
855
|
+
} else if (!opts) {
|
|
856
|
+
opts = {};
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
if (!this._agent.isStarted() || !this._agent._apmClient) {
|
|
860
|
+
if (cb) process.nextTick(cb);
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
const event = this._agent._eventFilters.process(_buildEvent(type, opts));
|
|
865
|
+
if (event) {
|
|
866
|
+
this._agent._apmClient.sendToChannel(this._name, 'event', event);
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
if (opts.error != null) {
|
|
870
|
+
this._agent.writeError(opts.error);
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
if (cb) process.nextTick(cb);
|
|
874
|
+
};
|
|
875
|
+
|
|
876
|
+
Channel.prototype.writeEvents = function (events, cb) {
|
|
877
|
+
if (!Array.isArray(events) || events.length === 0) {
|
|
878
|
+
if (cb) process.nextTick(cb);
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
if (!this._agent.isStarted() || !this._agent._apmClient) {
|
|
883
|
+
if (cb) process.nextTick(cb);
|
|
884
|
+
return;
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
for (const item of events) {
|
|
888
|
+
const event = this._agent._eventFilters.process(_buildEvent(item.type, item));
|
|
889
|
+
if (event) {
|
|
890
|
+
this._agent._apmClient.sendToChannel(this._name, 'event', event);
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
if (cb) process.nextTick(cb);
|
|
895
|
+
};
|
|
896
|
+
|
|
897
|
+
Channel.prototype.writeError = function (err, opts, cb) {
|
|
898
|
+
// Delegate to the agent (errors always go to the default channel)
|
|
899
|
+
this._agent.writeError(err, opts, cb);
|
|
900
|
+
};
|
|
901
|
+
|
|
902
|
+
Channel.prototype.writeTransaction = function (input) {
|
|
903
|
+
if (!this._agent._apmClient || !input) return;
|
|
904
|
+
const transaction = _validateTransaction(input);
|
|
905
|
+
if (transaction) {
|
|
906
|
+
this._agent._apmClient.sendToChannel(this._name, 'transaction', transaction);
|
|
907
|
+
}
|
|
908
|
+
};
|
|
909
|
+
|
|
910
|
+
Channel.prototype.writeSpan = function (input) {
|
|
911
|
+
if (!this._agent._apmClient || !input) return;
|
|
912
|
+
const span = _validateSpan(input);
|
|
913
|
+
if (span) {
|
|
914
|
+
this._agent._apmClient.sendToChannel(this._name, 'span', span);
|
|
915
|
+
}
|
|
916
|
+
};
|
|
917
|
+
|
|
918
|
+
// --- Write transaction/span on the default channel ---
|
|
919
|
+
|
|
920
|
+
// Write a validated transaction record to the default channel.
|
|
921
|
+
Agent.prototype.writeTransaction = function (input) {
|
|
922
|
+
if (!this._apmClient || !input) return;
|
|
923
|
+
const transaction = _validateTransaction(input);
|
|
924
|
+
if (transaction) {
|
|
925
|
+
this._apmClient.sendTransaction(transaction);
|
|
926
|
+
}
|
|
927
|
+
};
|
|
928
|
+
|
|
929
|
+
// Write a validated span record to the default channel.
|
|
930
|
+
Agent.prototype.writeSpan = function (input) {
|
|
931
|
+
if (!this._apmClient || !input) return;
|
|
932
|
+
const span = _validateSpan(input);
|
|
933
|
+
if (span) {
|
|
934
|
+
this._apmClient.sendSpan(span);
|
|
935
|
+
}
|
|
936
|
+
};
|
|
937
|
+
|
|
938
|
+
// Backward compat aliases
|
|
939
|
+
Agent.prototype.captureEvent = Agent.prototype.writeEvent;
|
|
940
|
+
Agent.prototype.captureEvents = Agent.prototype.writeEvents;
|
|
941
|
+
Agent.prototype.captureError = Agent.prototype.writeError;
|
|
942
|
+
Agent.prototype.writeClientTransaction = Agent.prototype.writeTransaction;
|
|
943
|
+
Agent.prototype.writeClientSpan = Agent.prototype.writeSpan;
|
|
944
|
+
|
|
945
|
+
// --- Validation helpers for transaction/span records ---
|
|
946
|
+
|
|
947
|
+
const HEX_16 = /^[0-9a-f]{16}$/;
|
|
948
|
+
const HEX_32 = /^[0-9a-f]{32}$/;
|
|
949
|
+
const VALID_OUTCOMES = ['success', 'failure', 'unknown'];
|
|
950
|
+
|
|
951
|
+
function _validateTransaction(input) {
|
|
952
|
+
const id = typeof input.id === 'string' && HEX_16.test(input.id) ? input.id : null;
|
|
953
|
+
const trace_id = typeof input.trace_id === 'string' && HEX_32.test(input.trace_id) ? input.trace_id : null;
|
|
954
|
+
if (!id || !trace_id) return null;
|
|
955
|
+
|
|
956
|
+
const transaction = {
|
|
957
|
+
id,
|
|
958
|
+
trace_id,
|
|
959
|
+
timestamp: typeof input.timestamp === 'number' && isFinite(input.timestamp) ? Math.floor(input.timestamp) : Date.now() * 1000,
|
|
960
|
+
outcome: VALID_OUTCOMES.includes(input.outcome) ? input.outcome : 'unknown',
|
|
961
|
+
sampled: input.sampled === true,
|
|
962
|
+
span_count: { started: typeof input.span_count?.started === 'number' ? input.span_count.started : 0 },
|
|
963
|
+
};
|
|
964
|
+
|
|
965
|
+
if (typeof input.name === 'string') transaction.name = input.name.slice(0, 1024);
|
|
966
|
+
if (typeof input.type === 'string') transaction.type = input.type.slice(0, 1024);
|
|
967
|
+
if (typeof input.duration === 'number' && isFinite(input.duration)) transaction.duration = input.duration;
|
|
968
|
+
if (typeof input.result === 'string') transaction.result = input.result.slice(0, 1024);
|
|
969
|
+
if (typeof input.parent_id === 'string' && HEX_16.test(input.parent_id)) transaction.parent_id = input.parent_id;
|
|
970
|
+
if (input.context && typeof input.context === 'object') {
|
|
971
|
+
const ctx = _sanitizeContext(input.context);
|
|
972
|
+
if (ctx) transaction.context = ctx;
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
return transaction;
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
function _validateSpan(input) {
|
|
979
|
+
const id = typeof input.id === 'string' && HEX_16.test(input.id) ? input.id : null;
|
|
980
|
+
const trace_id = typeof input.trace_id === 'string' && HEX_32.test(input.trace_id) ? input.trace_id : null;
|
|
981
|
+
const transaction_id = typeof input.transaction_id === 'string' && HEX_16.test(input.transaction_id) ? input.transaction_id : null;
|
|
982
|
+
const parent_id = typeof input.parent_id === 'string' && HEX_16.test(input.parent_id) ? input.parent_id : null;
|
|
983
|
+
if (!id || !trace_id || !transaction_id || !parent_id) return null;
|
|
984
|
+
|
|
985
|
+
const span = {
|
|
986
|
+
id,
|
|
987
|
+
trace_id,
|
|
988
|
+
transaction_id,
|
|
989
|
+
parent_id,
|
|
990
|
+
timestamp: typeof input.timestamp === 'number' && isFinite(input.timestamp) ? Math.floor(input.timestamp) : Date.now() * 1000,
|
|
991
|
+
sync: input.sync === true,
|
|
992
|
+
outcome: VALID_OUTCOMES.includes(input.outcome) ? input.outcome : 'unknown',
|
|
993
|
+
};
|
|
994
|
+
|
|
995
|
+
if (typeof input.name === 'string') span.name = input.name.slice(0, 1024);
|
|
996
|
+
if (typeof input.type === 'string') span.type = input.type.slice(0, 1024);
|
|
997
|
+
if (typeof input.duration === 'number' && isFinite(input.duration)) span.duration = input.duration;
|
|
998
|
+
if (typeof input.subtype === 'string') span.subtype = input.subtype.slice(0, 1024);
|
|
999
|
+
if (typeof input.action === 'string') span.action = input.action.slice(0, 1024);
|
|
1000
|
+
if (input.context && typeof input.context === 'object') {
|
|
1001
|
+
const ctx = _sanitizeContext(input.context);
|
|
1002
|
+
if (ctx) span.context = ctx;
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
return span;
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
// Sanitize the context object for client-originated records.
|
|
1009
|
+
// Only allows tags (with primitive values) and user (with string fields).
|
|
1010
|
+
function _sanitizeContext(ctx) {
|
|
1011
|
+
const result = {};
|
|
1012
|
+
|
|
1013
|
+
if (ctx.tags && typeof ctx.tags === 'object') {
|
|
1014
|
+
const tags = {};
|
|
1015
|
+
for (const [k, v] of Object.entries(ctx.tags)) {
|
|
1016
|
+
if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {
|
|
1017
|
+
tags[k] = v;
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
if (Object.keys(tags).length > 0) result.tags = tags;
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
if (ctx.user && typeof ctx.user === 'object') {
|
|
1024
|
+
const user = {};
|
|
1025
|
+
if (typeof ctx.user.id === 'string') user.id = ctx.user.id;
|
|
1026
|
+
if (typeof ctx.user.email === 'string') user.email = ctx.user.email;
|
|
1027
|
+
if (typeof ctx.user.username === 'string') user.username = ctx.user.username;
|
|
1028
|
+
if (Object.keys(user).length > 0) result.user = user;
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
return Object.keys(result).length > 0 ? result : undefined;
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
function _buildEvent(type, opts) {
|
|
1035
|
+
const event = {
|
|
1036
|
+
type: type || 'custom',
|
|
1037
|
+
timestamp: opts.timestamp || Date.now(),
|
|
1038
|
+
};
|
|
1039
|
+
if (opts.message != null) event.message = opts.message;
|
|
1040
|
+
if (opts.level != null) event.level = opts.level;
|
|
1041
|
+
if (opts.duration != null) event.duration = opts.duration;
|
|
1042
|
+
if (opts.user != null) event.user = opts.user;
|
|
1043
|
+
if (opts.client != null) event.client = opts.client;
|
|
1044
|
+
if (opts.params != null) event.params = opts.params;
|
|
1045
|
+
if (opts.error != null) {
|
|
1046
|
+
const err = opts.error;
|
|
1047
|
+
event.error = {};
|
|
1048
|
+
if (isError(err)) {
|
|
1049
|
+
event.error.message = String(err.message || '');
|
|
1050
|
+
if (err.name) event.error.type = String(err.name);
|
|
1051
|
+
if (err.code) event.error.code = String(err.code);
|
|
1052
|
+
if (err.stack) event.error.stack = String(err.stack);
|
|
1053
|
+
} else if (typeof err === 'string') {
|
|
1054
|
+
event.error.message = err;
|
|
1055
|
+
} else {
|
|
1056
|
+
event.error.message = String(err);
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
return event;
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
// The optional callback will be called with the error object after the error
|
|
1063
|
+
// have been sent to the intake API. If no callback have been provided we will
|
|
1064
|
+
// automatically terminate the process, so if you provide a callback you must
|
|
1065
|
+
// remember to terminate the process manually.
|
|
1066
|
+
Agent.prototype.handleUncaughtExceptions = function (cb) {
|
|
1067
|
+
var agent = this;
|
|
1068
|
+
|
|
1069
|
+
if (this._uncaughtExceptionListener) {
|
|
1070
|
+
process.removeListener(
|
|
1071
|
+
'uncaughtException',
|
|
1072
|
+
this._uncaughtExceptionListener,
|
|
1073
|
+
);
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
this._uncaughtExceptionListener = function (err) {
|
|
1077
|
+
agent.logger.debug({ err }, 'Tracelog caught unhandled exception');
|
|
1078
|
+
// This somewhat mimics Node.js's core printing of the error to stderr, but
|
|
1079
|
+
// is not quite the same output. Compare to:
|
|
1080
|
+
// https://github.com/nodejs/node/blob/v20.5.0/src/node_errors.cc#L246-L266
|
|
1081
|
+
console.error(err);
|
|
1082
|
+
|
|
1083
|
+
agent.captureError(err, { handled: false }, function () {
|
|
1084
|
+
cb ? cb(err) : process.exit(1);
|
|
1085
|
+
});
|
|
1086
|
+
};
|
|
1087
|
+
|
|
1088
|
+
process.on('uncaughtException', this._uncaughtExceptionListener);
|
|
1089
|
+
};
|
|
1090
|
+
|
|
1091
|
+
// Flush all ended APM events (transactions, spans, errors, metricsets) to APM
|
|
1092
|
+
// server as soon as possible. If the optional `cb` is given, it will be called
|
|
1093
|
+
// `cb(flushErr)` when this is complete. If no `cb` is given, then a `Promise`
|
|
1094
|
+
// will be returned, which will either resolve with `void` or reject with
|
|
1095
|
+
// `flushErr`.
|
|
1096
|
+
//
|
|
1097
|
+
// Encoding and passing event data to the agent's transport is *asynchronous*
|
|
1098
|
+
// for some event types: spans and errors. This flush will make a *best effort*
|
|
1099
|
+
// attempt to wait for those "inflight" events to finish processing before
|
|
1100
|
+
// flushing data to APM server. To avoid `.flush()` hanging, this times out
|
|
1101
|
+
// after one second.
|
|
1102
|
+
//
|
|
1103
|
+
// If flush is called while still waiting for inflight events in an earlier
|
|
1104
|
+
// flush call, then the more recent flush will only wait for events that were
|
|
1105
|
+
// newly inflight *since the last .flush()* call. I.e. the second flush does
|
|
1106
|
+
// *not* wait for the set of events the first flush is waiting on. This makes
|
|
1107
|
+
// the semantics of flush less than ideal (one cannot blindly call .flush() to
|
|
1108
|
+
// flush *everything* that has come before). However it handles the common use
|
|
1109
|
+
// case of flushing synchronously after ending a span or capturing an error:
|
|
1110
|
+
// mySpan.end()
|
|
1111
|
+
// await apm.flush()
|
|
1112
|
+
// and it simplifies the implementation.
|
|
1113
|
+
//
|
|
1114
|
+
// # Dev Notes
|
|
1115
|
+
//
|
|
1116
|
+
// To support the implementation, agent code that creates an inflight event
|
|
1117
|
+
// must do the following:
|
|
1118
|
+
// - Take a reference to the current set of inflight events:
|
|
1119
|
+
// const inflightEvents = agent._inflightEvents
|
|
1120
|
+
// - Add a unique ID for the event to the set:
|
|
1121
|
+
// inflightEvents.add(id)
|
|
1122
|
+
// - Delete the ID from the set when sent to the transport (`.sendSpan(...)` et
|
|
1123
|
+
// al) or when dropping the event (e.g. because of a filter):
|
|
1124
|
+
// inflightEvents.delete(id)
|
|
1125
|
+
Agent.prototype.flush = function (cb) {
|
|
1126
|
+
// This 1s timeout is a subjective balance between "long enough for spans
|
|
1127
|
+
// and errors to reasonably encode" and "short enough to not block data
|
|
1128
|
+
// being reported to APM server".
|
|
1129
|
+
const DEFAULT_INFLIGHT_FLUSH_TIMEOUT_MS = 1000;
|
|
1130
|
+
|
|
1131
|
+
// shared options for the private `._flush()` API.
|
|
1132
|
+
const opts = { inflightTimeoutMs: DEFAULT_INFLIGHT_FLUSH_TIMEOUT_MS };
|
|
1133
|
+
|
|
1134
|
+
if (typeof cb !== 'function') {
|
|
1135
|
+
return new Promise((resolve, reject) => {
|
|
1136
|
+
this._flush(opts, (err) => {
|
|
1137
|
+
if (err) {
|
|
1138
|
+
reject(err);
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
resolve();
|
|
1142
|
+
});
|
|
1143
|
+
});
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
return this._flush(opts, cb);
|
|
1147
|
+
};
|
|
1148
|
+
|
|
1149
|
+
// The internal-use `.flush()` that supports some options not exposed to the
|
|
1150
|
+
// public API.
|
|
1151
|
+
//
|
|
1152
|
+
// @param {Number} opts.inflightTimeoutMs - Required. The number of ms to wait
|
|
1153
|
+
// for inflight events (spans, errors) to finish being send to the transport
|
|
1154
|
+
// before flushing.
|
|
1155
|
+
Agent.prototype._flush = function (opts, cb) {
|
|
1156
|
+
if (!this._apmClient) {
|
|
1157
|
+
// Log an *err* to provide a stack for the user.
|
|
1158
|
+
const err = new Error('cannot flush agent before it is started');
|
|
1159
|
+
this.logger.warn({ err }, err.message);
|
|
1160
|
+
if (cb) {
|
|
1161
|
+
process.nextTick(cb);
|
|
1162
|
+
}
|
|
1163
|
+
return;
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
const boundCb = cb && this._instrumentation.bindFunction(cb);
|
|
1167
|
+
|
|
1168
|
+
// If there are no inflight events then avoid creating additional objects.
|
|
1169
|
+
if (this._inflightEvents.size === 0) {
|
|
1170
|
+
this._apmClient.flush(boundCb);
|
|
1171
|
+
return;
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
// Otherwise, there are inflight events to wait for. Setup a handler to
|
|
1175
|
+
// callback when the current set of inflight events complete.
|
|
1176
|
+
const flushingInflightEvents = this._inflightEvents;
|
|
1177
|
+
flushingInflightEvents.setDrainHandler((drainErr) => {
|
|
1178
|
+
// The only possible drainErr is a timeout. This is best effort, so we only
|
|
1179
|
+
// log this and move on.
|
|
1180
|
+
this.logger.debug(
|
|
1181
|
+
{
|
|
1182
|
+
numRemainingInflightEvents: flushingInflightEvents.size,
|
|
1183
|
+
err: drainErr,
|
|
1184
|
+
},
|
|
1185
|
+
'flush: drained inflight events',
|
|
1186
|
+
);
|
|
1187
|
+
|
|
1188
|
+
// Then, flush the intake request to APM server.
|
|
1189
|
+
this._apmClient.flush(boundCb);
|
|
1190
|
+
}, opts.inflightTimeoutMs);
|
|
1191
|
+
|
|
1192
|
+
// Create a new empty set to collect subsequent inflight events.
|
|
1193
|
+
this._inflightEvents = new InflightEventSet();
|
|
1194
|
+
};
|
|
1195
|
+
|
|
1196
|
+
Agent.prototype.registerMetric = function (name, labelsOrCallback, callback) {
|
|
1197
|
+
var labels;
|
|
1198
|
+
if (typeof labelsOrCallback === 'function') {
|
|
1199
|
+
callback = labelsOrCallback;
|
|
1200
|
+
} else {
|
|
1201
|
+
labels = labelsOrCallback;
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
if (typeof callback !== 'function') {
|
|
1205
|
+
this.logger.error("Can't add callback of type %s", typeof callback);
|
|
1206
|
+
return;
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
this._metrics.getOrCreateGauge(name, callback, labels);
|
|
1210
|
+
};
|
|
1211
|
+
|
|
1212
|
+
/**
|
|
1213
|
+
* Return true iff the given metric name is "disabled", according to the
|
|
1214
|
+
* `disableMetrics` config var.
|
|
1215
|
+
*
|
|
1216
|
+
* @returns {boolean}
|
|
1217
|
+
*/
|
|
1218
|
+
Agent.prototype._isMetricNameDisabled = function (name) {
|
|
1219
|
+
const regexps = this._conf.disableMetricsRegExp;
|
|
1220
|
+
for (var i = 0; i < regexps.length; i++) {
|
|
1221
|
+
if (regexps[i].test(name)) {
|
|
1222
|
+
return true;
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
return false;
|
|
1226
|
+
};
|