New Relic for Node.js automatically instruments most standard web requests, but sometimes you want expanded instrumentation. With the agent's custom instrumentation API, you can create instrumentation for otherwise unsupported web frameworks, datastores, and message service clients.
The Node.js agent's custom instrumentation API also allows you to:
Create web transactions (useful for things like web sockets, where transactions can't be automatically created).
Beginning with Node.js agent version 2.0.0, New Relic provides an API to expand instrumentation for additional web frameworks. For more information, including a tutorial, see the documentation for the Node.js web framework instrumentation on GitHub.
Instrument unsupported message service clients
Beginning with Node.js agent version 2.0.0, New Relic provides an API to expand instrumentation for additional message service libraries. For more information, including a tutorial, see the documentation for the Node.js message service client instrumentation on GitHub.
Instrument unsupported datastores
Beginning with Node.js agent version 2.0.0, New Relic provides an API to expand instrumentation for additional datastore libraries. For more information, including a tutorial, see the documentation for the Node.js datastore instrumentation on GitHub.
Instrument web transactions
In order to create custom web transactions, call startWebTransaction to start the transaction. To end the transaction, use any of these options:
Ending the transaction
Comments
Promise
If the handler passed to startWebTransaction returns a promise, the agent will end the transaction when the returned promise resolves or rejects.
Manual
If you call getTransaction in the context of the new transaction, this notifies the agent that the transaction will be handled manually.
If getTransaction is called in the handler, then you must end the transaction by calling transaction.end().
Synchronous
If neither of these options are fulfilled, the transaction will be ended when the handler returns synchronously.
This example instruments a /websocket/ping transaction, a /websocket/update transaction, and a /websocket/new-message transaction within socket.io. The /ping example is synchronous, while the /new-message and /update examples are asynchronous.
This method only gives basic timing data for the transaction created. To create more intricate timing data and transaction naming for a particular framework, see the Node.js API docs and the related WebFramework tutorial on GitHub.
Instrument background transactions
You can use custom transactions to instrument non-web transactions (background tasks); for example:
Periodic jobs within your app
Work that continues after a request completes
To instrument background tasks, call startBackgroundTransaction in your handler to start a background transaction. To end the transaction, use any of these options:
Ending the transaction
Comments
Promise
If the handler passed to startBackgroundTransaction returns a promise, the agent will end the transaction when the returned promise resolves or rejects.
Manual
If you call getTransaction in the context of the new transaction, this notifies the agent that the transaction will be handled manually.
If getTransaction is called in the handler, then you must end the transaction by calling transaction.end().
Synchronous
If neither of these options are fulfilled, the transaction will be ended when the handler returns synchronously.
This example instruments update:cache within setInterval:
const nr =require('newrelic');
const redis =require('redis').createClient();
// Using API getTransaction to manage ending the transaction
You can create instrumentation using the instrumentation registration methods on the API. Writing instrumentation using the instrumentation API allows you to specify metrics and naming in greater detail by "monkey patching" methods (replacing functions) on relevant objects. Other options can offer visibility into web transactions that are already instrumented, or gain insight into databases and other in-transaction work that is not automatically instrumented.
To do this, wrap your callbacks in custom tracers. Custom tracers create and collect specific metrics for an additional segment within an existing transaction, such as a particular function or a database call.
To instrument individual callbacks, call startSegment() inside the callback, and move the main callback logic to the handler function.
To instrument a function that is called inside an asynchronous function, wrap both the target function and its parent asynchronous function with startSegment().
Important
These examples must be placed in code that is running under a transaction. The origin of the transaction, custom or automatically created, does not matter.
// This is recorded as the `db:createObject` segment.
db.createObject(cb);
},function(err, result){
// This is recorded as the callback to the `db:createObject` segment.
if(util.handleError(err, res)){
return;
}
res.write(JSON.stringify(result.rows[0].id));
res.write('\n');
res.end();
});
This example tracks both pg.connect and client.query. This is because client.query is called by an asynchronous parent function (pg.connect). Otherwise, you would not get any data from client.query. This allows startSegment() to propagate the active transaction across those asynchronous boundaries.
nr.startSegment('pg:connect',true,function(cb){
pg.connect(config.db_string, cb);
},function(err, client, done){
if(util.handleError(err,'500', res)){
returndone();
}
nr.startSegment('pg:query',true,function(cb){
client.query('SELECT count(*) FROM test_count', cb);
},function(err, result){
if(util.handleError(err,'500', res)){
returndone();
}
res.write(result.rows[0].count);
res.write('\n');
});
});
This example is the same as the callback one, but for interacting with a promise-based API. For promises, simply return the promise and call then after startSegment to continue your execution.
nr.startSegment('pg:connect',true,function(){
// This `pg:connect` segment will time until the returned promise
// either resolves or rejects.
return pg.connect(config.db_string);
}).then(function(client){
// The transaction context is propagated into following promises.
return client.query('SELECT count(*) FROM test_count');
}).then(function(result){
res.write(result.rows[0].count);
res.write('\n');
res.end();
},function(err){
// Error from querying.
util.handleError(err,'500', res);
}).finally(function(){
return client.release();
});
},function(err){
// Error from connecting.
util.handleError(err,'500', res);
});
This example shows how to instrument code using async/await to control asynchronous work. This requires using Node.js 8 or higher, as well as the New Relic for Node.js agent v2.3.0 or higher.