Integrations and Lifecycle
This page covers the remaining API methods: AWS Lambda handler wrapping, Apollo Server callbacks, SQL obfuscation, the dispatcher environment value, and shutting the agent down.
setLambdaHandler(handler)- Apollo Server callbacks
obfuscateSql(sql, dialect)setDispatcher(name, version)shutdown(options, callback)
setLambdaHandler(handler)
Wraps an AWS Lambda handler so each invocation becomes a transaction, with the event source detected from the event shape, cold start recording, and error capture.
'use strict'
const newrelic = require('newrelic')
module.exports.handler = newrelic.setLambdaHandler(async (event, context) => {
return { statusCode: 200, body: 'ok' }
})
Returns: the wrapped handler. If handler is not a function, it logs handler argument is not a function and cannot be recorded and returns it unchanged. The stub API (agent disabled) also returns the handler unchanged, so the same code runs without New Relic.
Response-streaming handlers (marked by the Lambda runtime as response streaming) are detected and recorded under the supportability metric Nodejs/Serverless/Lambda/ResponseStreaming.
Lambda needs serverless mode, which turns on automatically when AWS_LAMBDA_FUNCTION_NAME is set. See Serverless and Cloud for the related settings (account_id, apm_lambda_mode, logging defaults).
Apollo Server Callbacks
Three methods customize the @apollo/server instrumentation. Each takes a synchronous function; async or non-function arguments are rejected with a warning, and calling a method again replaces its previous callback.
setApolloOperationAttributesCallback(callback)
Called with Apollo's requestContext for each operation. Return an object; its entries are added as custom attributes (through addCustomAttributes).
newrelic.setApolloOperationAttributesCallback((requestContext) => ({
clientName: requestContext.request.http.headers.get('graphql-client-name')
}))
setApolloResolverAttributesCallback(callback)
Called for each resolver segment with { source, args, contextValue, info }. Return an object of custom attributes.
newrelic.setApolloResolverAttributesCallback(({ args, info }) => ({
allArgs: Object.keys(args).join(','),
returnType: info.returnType.name
}))
setApolloResolverFilterCallback(callback)
Decides whether a resolver segment is created for a field, to reduce span volume. Called with { source, args, contextValue, info }; return true to create the segment, false to skip it.
When registered, this callback is the only authority: it replaces the built-in logic that uses apollo_server.scalars and the top-level field rules.
newrelic.setApolloResolverFilterCallback(({ info }) =>
info.parentType.name === 'Query' ||
info.parentType.name === 'Mutation' ||
resolvers[info.parentType.name]?.[info.fieldName] != null
)
Related settings: apollo_server.scalars, introspection_queries, service_definition_queries, health_check_queries, field_metrics, collapse_field_metrics (see apollo_server).
obfuscateSql(sql, dialect)
Replaces literal values (quoted strings, numbers, and comments) in a SQL statement with ?, using the same obfuscator the agent applies to recorded queries.
| Parameter | Type | Description |
|---|---|---|
sql |
string | The SQL statement. |
dialect |
string | mysql, postgres, cassandra, oracle, or sqlite. Unknown or missing dialects use the mysql rules. |
newrelic.obfuscateSql("SELECT * FROM users WHERE email = '[email protected]' AND id = 42", 'postgres')
// 'SELECT * FROM users WHERE email = ? AND id = ?'
The dialect matters for quoting: for example, oracle understands q'[...]' quoting. Use this when you log or report queries yourself.
setDispatcher(name, version)
Sets the Dispatcher and Dispatcher Version environment values reported to New Relic — the component that brokers requests to your process (Node's http module is the default for web servers).
| Parameter | Type | Description |
|---|---|---|
name |
string | Required. Dispatcher name. |
version |
string or number | Optional. Converted to a string. Objects are ignored. |
Notes from the code:
- Only the first user call takes effect; later calls are ignored.
- A non-string or empty
namelogssetDispatcher must be called with a name, and name must be a string. - When
versionis omitted, the log linesetDispatcher was called with an object as the version parameteris still written at info level. It is harmless.
shutdown(options, callback)
Stops the agent, optionally sending pending data first. Use it at the end of scripts and short-lived jobs, or in signal handlers.
| Option | Type | Description |
|---|---|---|
collectPendingData |
boolean | Send collected data before stopping. |
timeout |
number | Milliseconds to wait for the agent to connect before giving up, when it is not yet connected. |
waitForIdle |
boolean | Wait until there are no active transactions before shutting down. |
Supported call forms: shutdown(), shutdown(options), shutdown(callback), shutdown(options, callback), and shutdown(null, callback).
process.on('SIGTERM', () => {
newrelic.shutdown({ collectPendingData: true, timeout: 3000 }, (err) => {
process.exit(err ? 1 : 0)
})
})
How it proceeds:
- If
waitForIdleis set and transactions are active, it waits for thetransactionFinishedevent until none remain, then continues. - If
collectPendingDatais set and the agent is already started, it forces a harvest of all data, then stops. - If
collectPendingDatais set but the agent has not finished starting, it waits for thestartedevent to harvest. If a numerictimeoutis set, a timer stops the agent after that delay instead. A non-numeric timeout logsoptions.timeout should be of type "number"and is ignored — without a timeout, an agent that never connects means the callback is never called. - Otherwise it stops immediately.
Errors during the final harvest are logged (An error occurred during last harvest before shutdown) and the agent still stops. The callback receives the result of agent.stop.