Agent APIedit

Note

This is the API documentation for the Elastic APM Node.js Agent. For getting started, we recommend that you take a look at our framework specific documentation for either Express, hapi, Koa, Restify, or custom frameworks.

The Elastic APM agent for Node.js is a singleton. You get the agent instance by either requiring elastic-apm-node or elastic-apm-node/start. For details on the two approaches, see the Setup and Configuration guide.

The agent is also returned by the start() function, which allows you to require and start the agent on the same line:

var apm = require('elastic-apm-node').start(...)

If you need to access the Agent in any part of your codebase, you can simply require elastic-apm-node to access the already started singleton. You therefore don’t need to manage or pass around the started Agent yourself.

apm.start()edit

apm.start([options])

Starts the Elastic APM agent for Node.js and returns itself.

Important

Put the call to this function at the very top of your main app file - before requiring any other modules.

If you are using Babel calling this function will not have the desired effect. See the Babel / ES Modules support documentation for details.

If you are using Typescript the import statement may be removed if it is not used. It is recommended to use -r elastic-apm-node/start when starting the app to avoid this.

See the Configuration documentation for available options.

apm.isStarted()edit

apm.isStarted()

Use isStarted() to check if the agent has already started. Returns true if the agent has started, otherwise returns false.

apm.addFilter()edit

apm.addFilter(callback)

Use addFilter() to supply a filter function.

Each filter function will be called just before data is being sent to the APM Server. This will allow you to manipulate the data being sent, for instance to remove sensitive information like passwords etc.

Each filter function will be called in the order they were added, and will receive a payload object as the only argument, containing the data about to be sent to the APM Server.

The format of the payload depends on the event type being sent. For details about the different formats, see the APM Server intake API documentation.

The filter function is synchronous and should return the manipulated payload object. If a filter function doesn’t return any value or returns a falsy value, the remaining filter functions will not be called and the payload will not be sent to the APM Server.

Example usage:

apm.addFilter(function (payload) {
  if (payload.context.request && payload.context.request.headers) {
    // redact sensitive data
    payload.context.request.headers['x-secret'] = '[REDACTED]'
  }

  // remember to return the modified payload
  return payload
})

A set of built-in filters are added by default. See filterHttpHeaders for details.

Though you can also use filter functions to add new contextual information to the user and custom properties, it’s recommended that you use apm.setUserContext() and apm.setCustomContext() for that purpose.

apm.addErrorFilter()edit

apm.addErrorFilter(callback)

Similar to apm.addFilter(), but the callback will only be called with error payloads.

apm.addTransactionFilter()edit

apm.addTransactionFilter(callback)

Similar to apm.addFilter(), but the callback will only be called with transaction payloads.

apm.addSpanFilter()edit

apm.addSpanFilter(callback)

Similar to apm.addFilter(), but the callback will only be called with span payloads.

apm.setUserContext()edit

apm.setUserContext(context)

Call this to enrich collected performance data and errors with information about the user/client. This function can be called at any point during the request/response life cycle (i.e. while a transaction is active).

The given context argument must be an object and can contain the following properties (all optional):

  • id - The user’s ID
  • username - The user’s username
  • email - The user’s e-mail

The given context will be added to the active transaction. If no active transaction can be found, false is returned. Otherwise true.

It’s possible to call this function multiple times within the scope of the same active transaction. For each call, the properties of the context argument are shallow merged with the context previously given.

If an error is captured, the context from the active transaction is used as context for the captured error, and any custom context given as the 2nd argument to apm.captureError takes precedence and is shallow merged on top.

The provided user context is stored under context.user in Elasticsearch on both errors and transactions.

apm.setCustomContext()edit

apm.setCustomContext(context)

Call this to enrich collected errors and transactions with any information that you think will help you debug performance issues or errors. This function can be called at any point while a transaction is active (e.g. during the request/response life cycle of an incoming HTTP request).

The provided custom context is stored under context.custom in Elasticsearch on both errors and transactions.

The given context argument must be an object and can contain any property that can be JSON encoded.

The given context will be added to the active transaction. If no active transaction can be found, false is returned. Otherwise true.

It’s possible to call this function multiple times within the scope of the same active transaction. For each call, the properties of the context argument are shallow merged with the context previously given.

If an error is captured, the context from the active transaction is used as context for the captured error, and any custom context given as the 2nd argument to apm.captureError takes precedence and is shallow merged on top.

apm.setTag()edit

apm.setTag(name, value)

Set a tag on the current transaction. You can set multiple tags on the same transaction. If an error happens during the current transaction, it will also get tagged with the same tags.

Tags are key/value pairs that are indexed by Elasticsearch and therefore searchable (as opposed to data set via setCustomContext()).

Arguments:

  • name - Any string. Must not contain periods (.) as those have special meaning in Elasticsearch
  • value - Any string. If a non-string data type is given, it’s converted to a string before being sent to the APM Server

apm.addTags()edit

apm.addTags({ [name]: value })

Add several tags on the current transaction. You can add tags multiple times. If an error happens during the current transaction, it will also get tagged with the same tags.

Tags are key/value pairs that are indexed by Elasticsearch and therefore searchable (as opposed to data set via setCustomContext()).

Arguments:

  • name - Any string. Must not contain periods (.) as those have special meaning in Elasticsearch
  • value - Any string. If a non-string data type is given, it’s converted to a string before being sent to the APM Server

apm.captureError()edit

apm.captureError(error[, options][, callback])

Send an error to the APM Server:

apm.captureError(new Error('boom!'))

The error argument can be either an Error object, a message string, or a special parameterized message object.

The optional options object can be used to log additional metadata with the error. For details see the metadata section.

The optional callback will be called after the error has been sent to the APM Server. It will receive an Error instance if the agent failed to send the error, and the id of the captured error.

Message stringsedit

Instead of an Error object, you can log a plain text message:

apm.captureError('Something happened!')

This will also be sent as an error to the APM Server, but will not be associated with an exception.

Parameterized message objectedit

Instead of an Error object or a string, you can supply a special parameterized message object:

apm.captureError({
  message: 'Could not find user %s with id %d in the database',
  params: ['Peter', 42]
})

This makes it possible to better group error messages that contain variable data like ID’s or names.

Metadataedit

To ease debugging it’s possible to send some extra data with each error you send to the APM Server. The APM Server intake API supports a lot of different metadata fields, most of which are automatically managed by the Elastic APM Node.js Agent. But if you wish you can supply some extra details using user or custom. For more details on the properties accepted by the events intake API see the events intake API docs.

To supply any of these extra fields, use the optional options argument when calling apm.captureError().

Here are some examples:

// Sending some extra details about the user
apm.captureError(error, {
  user: {
    id: 'unique_id',
    username: 'foo',
    email: 'foo@example.com'
  }
})

// Sending some arbitrary details using the `custom` field
apm.captureError(error, {
  custom: {
    some_important_metric: 'foobar'
  }
})

To supply per-request metadata to all errors captured in one central location, use apm.setUserContext() and apm.setCustomContext().

HTTP requestsedit

Besides the options described in the metadata section, you can use the options argument to associate the error with an HTTP request:

apm.captureError(err, {
  request: req // an instance of http.IncomingMessage
})

This will log the URL that was requested, the HTTP headers, cookies and other useful details to help you debug the error.

In most cases, this isn’t needed, as the agent is pretty smart at figuring out if your Node.js app is an HTTP server and if an error occurred during an incoming request. In which case it will automate this processes for you.

HTTP responsesedit

Besides the options described in the metadata section, you can use the options argument to associate the error with an HTTP response:

apm.captureError(err, {
  response: res // an instance of http.ServerResponse
})

This will log the response status code, headers and other useful details to help you debug the error.

In most cases, this isn’t needed, as the agent is pretty smart at figuring out if your Node.js app is an HTTP server and if an error occurred during an incoming request. In which case it will automate this processes for you.

apm.middleware.connect()edit

apm.middleware.connect()

Returns a middleware function used to collect and send errors to the APM Server.

var apm = require('elastic-apm-node').start()
var connect = require('connect')

var app = connect()

// your regular middleware:
app.use(...)
app.use(...)

// your main HTTP router
app.use(function (req, res, next) {
  throw new Error('Broke!')
})

// add Elastic APM in the bottom of the middleware stack
app.use(apm.middleware.connect())

app.listen(3000)
Note

apm.middleware.connect must be added to the middleware stack before any other error handling middleware functions or there’s a chance that the error will never get to the agent.

apm.startTransaction()edit

var transaction = apm.startTransaction([name][, type][, traceparent])

Start a new transaction.

Arguments:

  • name - The name of the transaction (string). You can always set this later via transaction.name or apm.setTransactionName(). Defaults to unnamed
  • type - The type of transaction (string). You can always set this later via transaction.type. Defaults to custom
  • traceparent - The traceparent header received from a remote service (string).

Use this function to create a custom transaction. Note that the agent will do this for you automatically whenever your application receives an incoming HTTP request. You only need to use this function to create custom transactions.

There’s a special type called request which is used by the agent for the transactions automatically created when an incoming HTTP request is detected.

See the Transaction API docs for details on how to use custom transactions.

apm.endTransaction([result])edit

apm.endTransaction([result])

Ends the active transaction. If no transaction is currently active, nothing happens.

Note that the agent will do this for you automatically for all regular HTTP transactions. You only need to use this function to end custom transactions created by apm.startTransaction() or if you wish the end a regular transaction prematurely.

Alternatively you can call end() directly on an active transaction object.

A value may be provided to set as a result.

apm.currentTransactionedit

var transaction = apm.currentTransaction

Get the currently active transaction, if used within the context of a transaction.

Note

If there’s no active transaction available, null will be returned.

apm.setTransactionName()edit

apm.setTransactionName(name)

Set or overwrite the name of the current transaction. The name argument must be a string.

If you use a supported router/framework the agent will automatically set the transaction name for you.

If you do not use Express, hapi, koa-router, or restify or if the agent for some reason cannot detect the name of the HTTP route, the transaction name will default to METHOD unknown route (e.g. POST unknown route).

Read more about naming routes manually in the Get started with a custom Node.js stack article.

apm.startSpan([name][, type])edit

var span = apm.startSpan('My custom span')

Start and return a new custom span associated with the current active transaction. This is the same as getting the current transaction with apm.currentTransaction and, if a transaction was found, calling transaction.startSpan(name, type) on it.

Arguments:

  • name - The name of the span (string). You can alternatively set this via span.name. Defaults to unnamed
  • type - The type of span (string). You can alternatively set this via span.type. Defaults to custom.code

When a span is started it will measure the time until span.end() is called.

See Span API docs for details on how to use custom spans.

Note

If there’s no active transaction available, null will be returned.

apm.handleUncaughtExceptions()edit

apm.handleUncaughtExceptions([callback])

By default, the agent will terminate the Node.js process when an uncaught exception is detected. Use this function if you need to run any custom code before the process is terminated.

apm.handleUncaughtExceptions(function (err) {
  // Do your own stuff... and then exit:
  process.exit(1)
})

The callback is called after the event has been sent to the APM Server with the following arguments:

  • err - the captured exception

This function will also enable the uncaught exception handler if it was disabled using the captureExceptions configuration option.

If you don’t specify a callback, the node process is terminated automatically when an uncaught exception has been captured and sent to the APM Server.

It is recommended that you don’t leave the process running after receiving an uncaught exception, so if you are using the optional callback, remember to terminate the node process.

apm.flush([callback])edit

apm.flush(function (err) {
  // Flush complete
})

Manually end the active outgoing HTTP request to the APM Server. The HTTP request is otherwise ended automatically at regular intervals, controlled by the apiRequestTime and apiRequestSize config options.

The callback is called after the active HTTP request has ended. The callback is called even if no HTTP request is currently active.

apm.lambda([type, ] handler)edit

exports.hello = apm.lambda(function (payload, context, callback) {
  callback(null, `Hello, ${payload.name}!`)
})

Manually instrument a lambda function to form a transaction around each execution. Optionally, a type may also be provided to group lambdas together. By default, "lambda" will be used as the type name.

Read more lambda support in the Lambda article.