Agent APIedit

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.

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.

The available configuration options are listed below. Most configuration options can be set either in the optional options object, by using environment variables, or via the agent configuration file. Their equivalent environment variable name is listed together with each option.

Properties on the options object will always take precedence over environment variables.

The only required parameter is serviceName.

Example usage configuring the agent to only be active in production:

// Add this to the VERY top of the first file loaded in your app
require('elastic-apm-node').start({
  // Override service name from package.json
  // Allowed characters: a-z, A-Z, 0-9, -, _, and space
  serviceName: '',

  // Use if APM Server requires a token
  secretToken: '',

  // Set custom APM Server URL (default: http://localhost:8200)
  serverUrl: '',

  // Only activate the agent if it's running in production
  active: process.env.NODE_ENV === 'production'
})

serviceNameedit

  • Type: String
  • Default: name field of package.json
  • Env: ELASTIC_APM_SERVICE_NAME

Your Elastic APM service name.

secretTokenedit

  • Type: String
  • Env: ELASTIC_APM_SECRET_TOKEN

The secret token optionally expected by the APM Server.

serverUrledit

  • Type: String
  • Default: http://localhost:8200
  • Env: ELASTIC_APM_SERVER_URL

The URL to where the APM Server is deployed.

verifyServerCertedit

  • Type: Boolean
  • Default: true
  • Env: ELASTIC_APM_VERIFY_SERVER_CERT

By default the agent will validate the TLS/SSL certificate of the APM Server if using HTTPS. You can switch this behavior off by setting this option to false. Disabling validation is normally required if using self-signed certificates.

serviceVersionedit

  • Type: String
  • Env: ELASTIC_APM_SERVICE_VERSION

The version of the app currently running. This could be the version from your package.json file, a git commit reference, or any other string that might help you pinpoint a specific version or deployment.

activeedit

  • Type: Boolean
  • Default: true
  • Env: ELASTIC_APM_ACTIVE

A boolean specifying if the agent should be active or not. If active, the agent will instrument incoming HTTP requests and track errors. Normally you would not want to run the agent in your development or testing environments. If you are using the NODE_ENV environment variable, you can use this to determine the state:

var options = {
  active: process.env.NODE_ENV === 'production'
}

instrumentedit

  • Type: Boolean
  • Default: true
  • Env: ELASTIC_APM_INSTRUMENT

A boolean specifying if the agent should collect performance metrics for the app.

Note that both active and instrument needs to be true for instrumentation to be running.

asyncHooksedit

  • Type: Boolean
  • Default: true
  • Env: ELASTIC_APM_ASYNC_HOOKS

A boolean specifying if the agent should use the experimental Async Hooks API found in Node.js version 8.2.0 and above. This setting has no effect when running a Node.js version older than 8.2.0.

If you experience any issues related to using Async Hooks, please open an issue.

Note that not all core Node.js API’s can be instrumented without the use of Async Hooks if running Node.js 8 or above.

ignoreUrlsedit

  • Type: Array
  • Default: undefined

Used to restrict requests to certain URL’s from being instrumented.

This property should be set to an array containing one or more strings or RegExp objects. When an incoming HTTP request is detected, its URL will be tested against each element in this list. If an element in the array is a String, an exact match will be performed. If an element in the array is a RegExp object, its test function will be called with the URL being tested.

Note that all errors that are captured during a request to an ignored URL are still sent to the APM Server regardless of this setting.

Example usage:

require('elastic-apm-node').start({
  ignoreUrls: [
    '/ping',
    /^\/admin\//i
  ]
})

ignoreUserAgentsedit

  • Type: Array
  • Default: undefined

Used to restrict requests from certain User-Agents from being instrumented.

This property should be set to an array containing one or more strings or RegExp objects. When an incoming HTTP request is detected, the User-Agent from the request headers will be tested against each element in this list. If an element in the array is a String, it’s matched against the beginning of the User-Agent. If an element in the array is a RegExp object, its test function will be called with the User-Agent string being tested.

Note that all errors that are captured during a request by an ignored user agent are still sent to the APM Server regardless of this setting.

Example usage:

require('elastic-apm-node').start({
  ignoreUserAgents: [
    'curl/',
    /pingdom/i
  ]
})

captureBodyedit

  • Type: String
  • Default: off
  • Env: ELASTIC_APM_CAPTURE_BODY

The HTTP body of incoming HTTP requests is not recorded and sent to the APM Server by default.

Possible options are: off, all, errors, and transactions.

  • off - request bodies will never be reported
  • errors - request bodies will only be reported with errors
  • transactions - request bodies will only be reported with request transactions
  • all - request bodies will be reported with both errors and request transactions

The recorded body will be truncated if larger than 2 KiB.

For the agent to be able to access the body, the body needs to be available as a property on the incoming HTTP request object. The agent will look for the body on the following properties: req.json || req.body || req.payload

errorOnAbortedRequestsedit

  • Type: Boolean
  • Default: false
  • Env: ELASTIC_APM_ERROR_ON_ABORTED_REQUESTS

A boolean specifying if the agent should monitor for aborted TCP connections with un-ended HTTP requests. An error will be generated and sent to the APM Server if this happens.

abortedErrorThresholdedit

  • Type: Number
  • Default: 25000
  • Env: ELASTIC_APM_ABORTED_ERROR_THRESHOLD

Specify the threshold (in milliseconds) for when an aborted TCP connection with an un-ended HTTP request is considered an error.

If the errorOnAbortedRequests property is false, this property is ignored.

transactionSampleRateedit

  • Type: Number
  • Default: 1.0
  • Env: ELASTIC_APM_TRANSACTION_SAMPLE_RATE

Specify the sampling rate to use when deciding whether to trace a request.

The value should between 0.0 and 1.0 where 1.0 is 100% of all requests.

hostnameedit

  • Type: String
  • Default: OS hostname
  • Env: ELASTIC_APM_HOSTNAME

The OS hostname is automatically logged along with all errors and transactions. If you want to overwrite this, use this option.

frameworkNameedit

  • Type: String
  • Env: ELASTIC_APM_FRAMEWORK_NAME

Set the name of the web framework used by the instrumented service / application. The name will be available as metadata for all errors and transactions sent to the APM Server. This can be useful for debugging and filtering.

By default, the agent will set the value of this config option if the framework can be detected automatically.

frameworkVersionedit

  • Type: String
  • Env: ELASTIC_APM_FRAMEWORK_VERSION

Set the version of the web framework used by the instrumented service / application. The version will be available as metadata for all errors and transactions sent to the APM Server. This can be useful for debugging and filtering.

By default, the agent will set the value of this config option if the framework can be detected automatically.

Example of setting frameworkName and frameworkVersion for a framework named my-custom-framework:

// read the version from the package.json file
var frameworkVersion = require('my-custom-framework/package').version

require('elastic-apm-node').start({
  frameworkName: 'my-custom-framework',
  frameworkVersion: frameworkVersion
})

logLeveledit

  • Type: String
  • Default: 'info'
  • Env: ELASTIC_APM_LOG_LEVEL

Set the verbosity level for the agent. Note that this does not have any influence on the types of errors that are sent to the APM Server. This only controls how chatty the agent is in your logs. This only applies when not using a custom logger.

Possible levels are: trace, debug, info, warn, error, and fatal.

loggeredit

  • Type: object

Set a custom logger, e.g. bunyan:

require('elastic-apm-node').start({
  logger: require('bunyan')({ level: 'info' })
})

If no custom logger is provided, the agent will use its built-in logger which will log to STDOUT and STDERR depending on the log level.

The logger should expose the following functions: trace, debug,info, warn, error, and fatal.

Note that if a custom logger is provided, the logLevel option will be ignored.

captureExceptionsedit

  • Type: Boolean
  • Default: true
  • Env: ELASTIC_APM_CAPTURE_EXCEPTIONS

Whether or not the agent should monitor for uncaught exceptions and send them to the APM Server automatically.

captureErrorLogStackTracesedit

  • Type: String
  • Default: messages
  • Env: ELASTIC_APM_CAPTURE_ERROR_LOG_STACK_TRACES

Normally only Error objects have a stack trace associated with them. This stack trace is stored along with the error message when the error is sent to the APM Server. The stack trace points to the place where the Error object was instantiated.

But sometimes its valuable to know, not where the Error was instantiated, but where it was detected. For instance, when an error happens deep within a database driver, the location where the error bubbles up to, is sometimes more useful for debugging, than where the error occurred.

Set this config option to always to — besides the error stack trace — also capture a stack trace at the location where captureError was called.

By default, this config option has the value messages, which means that a stack trace of the capture location will be recorded only when captureError is called with either a string or the special parameterized message object, in which case a normal stack trace isn’t available.

Set this config option to never to never record a capture location stack trace.

A capture location stack trace is never generated for uncaught exceptions.

captureSpanStackTracesedit

  • Type: Boolean
  • Default: true
  • Env: ELASTIC_APM_CAPTURE_SPAN_STACK_TRACES

Set this option to false to disable capture of stack traces for measured spans during instrumentation.

sourceLinesErrorAppFrames + sourceLinesErrorLibraryFramesedit

When an error is captured by the agent, its stack trace is stored in Elasticsearch.

By default the agent will also collect a few lines of source code around the lines for each frame in the stack trace. This can make it easier to determine the cause of an error as the source code related to the error is visible directly in Kibana.

The agent differentiates between so called in-app frames and library frames. Library frames are frames belonging to Node core and code inside the applications node_modules folder. In-app frames are everything else.

Use the following two config options to change how many lines of source code to include for the different types of stack frames:

sourceLinesErrorAppFrames

  • Type: Number
  • Default: 5
  • Env: ELASTIC_APM_SOURCE_LINES_ERROR_APP_FRAMES

The default value 5 means that 5 lines of source code will be collected for in-app error frames. 2 lines above the stack frame line + 2 below + the stack frame line it self.

Setting this config option to 0 means that no source code will be collected for in-app error frames.

sourceLinesErrorLibraryFrames

  • Type: Number
  • Default: 5
  • Env: ELASTIC_APM_SOURCE_LINES_ERROR_LIBRARY_FRAMES

The default value 5 means that 5 lines of source code will be collected for error library frames. 2 lines above the stack frame line + 2 below + the stack frame line it self.

Setting this config option to 0 means that no source code will be collected for error library frames.

sourceLinesSpanAppFrames + sourceLinesSpanLibraryFramesedit

When a span is recorded by the agent, a stack trace is recorded together with the span, pointing to the location where the span was initiated. This stack trace is stored in Elasticsearch along with the other span data.

By default the agent will also collect a few lines of source code around the lines for each frame in the stack trace. This can make it easier to determine why and how the span was initiated as the source code related to the span is visible directly in Kibana.

The agent differentiates between so called in-app frames and library frames. Library frames are frames belonging to Node core and code inside the applications node_modules folder. In-app frames are everything else.

Use the following two config options to change how many lines of source code to include for the different types of stack frames:

sourceLinesSpanAppFrames

  • Type: Number
  • Default: 0
  • Env: ELASTIC_APM_SOURCE_LINES_SPAN_APP_FRAMES

The default value 0 means that no source code will be collected for in-app span frames.

sourceLinesSpanLibraryFrames

  • Type: Number
  • Default: 0
  • Env: ELASTIC_APM_SOURCE_LINES_SPAN_LIBRARY_FRAMES

The default value 0 means that no source code will be collected for span library frames.

errorMessageMaxLengthedit

  • Type: Number
  • Default: 2048
  • Env: ELASTIC_APM_ERROR_MESSAGE_MAX_LENGTH

The maximum length allowed for error messages in bytes. Messages above this length will be truncated before being sent to the APM Server.

Set to -1 do disable truncation.

This applies to the following properties:

  • error.exception.message
  • error.log.message

stackTraceLimitedit

  • Type: Number
  • Default: 50
  • Env: ELASTIC_APM_STACK_TRACE_LIMIT

Setting it to 0 will disable stack trace collection. Any finite integer value will be used as the maximum number of frames to collect. Setting it to Infinity means that all frames will be collected.

transactionMaxSpansedit

  • Type: Number
  • Default: 500
  • Env: ELASTIC_APM_TRANSACTION_MAX_SPANS

Specify the maximum number of spans to capture within a request transaction before dropping further spans. Setting to -1 means that spans will never be dropped.

flushIntervaledit

  • Type: Number
  • Default: 10
  • Env: ELASTIC_APM_FLUSH_INTERVAL

The agent maintains an in-memory queue to which recorded transactions are added when they end. Unless empty, this queue is flushed and sent to the APM Server for processing approximately every 10 seconds.

Use this option to change that interval. The value is expected to be in seconds.

Lowering this interval can reduce memory usage on Node.js applications with a high number of transactions.

The queue is flushed approximately 5 seconds after the first transaction has ended on a newly started Node process.

This ensures that you don’t have to wait for the entire flushInterval to pass for the first data to be sent to the APM Server. From there on the flushInterval option is used.

After each flush of the queue, the next flush isn’t scheduled until a transaction have ended.

This is done to introduce variance and also ensures that empty queues are not scheduled for flushing.

On top of that, the actual interval is adjusted by +/- 5% between each flush.

This all helps to ensure that multiple servers started at the same time will not establish connections to the APM Server simultaneously.

serverTimeoutedit

  • Type: Number
  • Default: 30
  • Env: ELASTIC_APM_SERVER_TIMEOUT

Specify the timeout in seconds when reporting transactions to APM Server.

maxQueueSizeedit

  • Type: Number
  • Default: 100
  • Env: ELASTIC_APM_MAX_QUEUE_SIZE

The agent maintains an in-memory queue to which recorded transactions are added when they end. The queue is flushed with regular intervals controlled by the flushInterval config option.

Use the maxQueueSize option to force a flush of the queue when it reaches a certain size (number of ended transactions) - even if the flushInterval time isn’t reached yet.

Set to -1 to disable, in which case only flushInterval counts.

filterHttpHeadersedit

  • Type: Boolean
  • Default: true
  • Env: ELASTIC_APM_FILTER_HTTP_HEADERS

When tracing an incoming HTTP request, the agent will add metadata about the requests to the recorded transaction. The same applies for errors that occurs and are captured as a result of the request.

This boolean specifies if the agent should anonymize certain sensitive HTTP headers by default before they are sent to the APM Server. When anonymized, the header value will be set to [REDACTED]

Currently the following HTTP headers are anonymized by default:

  • Authorization - The full value of this header is redacted
  • Cookie - The cookies inside the Cookie header are analyzed and their values redacted if they appear sensitive (like a session cookie). See the is-secret module for details about which patterns are considered sensitive.

If you wish to filter or sanitize other data, use the apm.addFilter() function.

disableInstrumentationsedit

  • Type: Array of strings
  • Env: ELASTIC_APM_DISABLE_INSTRUMENTATIONS

Array or comma-separated string of modules to disable instrumentation for. When instrumentation is disabled for a module, no spans will be collected for that module.

Example using options object:

require('elastic-apm-node').start({
  disableInstrumentations: ['graphql', 'express-graphql']
})

Example using environment variable:

ELASTIC_APM_DISABLE_INSTRUMENTATIONS=graphql,express-graphql

For an always up-to-date list of modules for which instrumentation can be disabled, see the lib/instrumentation/modules folder in the agent repository. Note that not all modules represented in this directory will generate spans, and adding those to this array has no effect.

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.

For details on the format of the payload, 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) {
  // the payload can either contain an array of transactions or errors
  var items = payload.transactions || payload.errors || []

  // loop over each item in the array to redact any secrets we don't
  // want sent to the APM Server
  items.forEach(function (item) {
    if (item.context.request && item.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.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 users ID
  • username - The users username
  • email - The users 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 error intake API see the intake error 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 though, 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 though, 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)

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])

Start a new transaction.

Arguments:

Use this function to create a custom transaction. Note that the agent will do this for you automatically when ever 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.

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.

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() or span.truncate() is called.

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

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

apm.buildSpan()edit

Deprecated in 1.1.0.

Replaced by <<apm-start-span

var span = apm.buildSpan()

Prepare and return a new custom span associated with the current active transaction.

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

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 flush the in-memory transaction queue and send all the transactions to the APM Server. The queue is otherwise flushed automatically, controlled by the flushInterval and/or maxQueueSize config options.

The callback is called after the event has been sent to the APM Server with a possible error argument.

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.