Custom Instrumentation

When the agent does not instrument a library you use — an in-house database client, a niche framework, a proprietary queue — you can register your own instrumentation. It runs when the module is loaded and receives a shim, the same helper object the agent's built-in instrumentation uses to wrap functions, create segments, and name transactions.

For simple cases, consider the transaction API first: startSegment and startBackgroundTransaction need no module hooks.

Registration Methods

All five methods share the same signatures:

newrelic.instrument(moduleName, onRequire, onError)
newrelic.instrument({ moduleName, onRequire, onError, absolutePath, isEsm })
Method Shim passed to onRequire Use for
instrument Shim (generic) Any library.
instrumentDatastore DatastoreShim Database and cache clients.
instrumentMessages MessageShim Message brokers and queues.
instrumentWebframework WebFrameworkShim HTTP frameworks (middleware, routing).
instrumentConglomerate ConglomerateShim Modules that mix categories (for example a client exposing both datastore and messaging APIs).

Options

Option Type Description
moduleName string Required. The name used to load the module (require('job-queue') → 'job-queue').
onRequire function Required. Called as onRequire(shim, moduleExports, moduleName) when the module is loaded.
onError function Optional. Receives the error if onRequire throws.
absolutePath string Absolute path of the module when it is a file in your application rather than a package in node_modules. moduleName must still be given.
isEsm boolean Set to true when instrumenting an ES module (see below).

Registration is validated: a missing options object, moduleName, or onRequire logs a warning such as Instrumentation registration failed, 'moduleName' not provided and does nothing.

Register before the module loads

Instrumentation applies when the module is loaded, so call newrelic.instrument* before the first require/import of that module — typically in a small file preloaded right after the agent:

node -r newrelic -r ./instrumentation.js app.js

A Complete Example

Assume a library job-queue exposing Queue.prototype.add(job, callback) and Queue.prototype.process(handler):

// instrumentation.js
'use strict'
const newrelic = require('newrelic')

newrelic.instrument({
  moduleName: 'job-queue',
  onRequire(shim, jobQueue) {
    const proto = jobQueue.Queue && jobQueue.Queue.prototype
    if (!proto) return

    // 1. Time each add() call as a segment named "JobQueue/add".
    shim.record(proto, 'add', function recordAdd(shim, fn, name, args) {
      return { name: 'JobQueue/add', callback: shim.LAST }
    })

    // 2. Make each processed job its own background transaction.
    shim.wrap(proto, 'process', function wrapProcess(shim, process) {
      return function wrappedProcess(handler) {
        const wrappedHandler = function (job, done) {
          return newrelic.startBackgroundTransaction('job', 'JobQueue', () => {
            const tx = newrelic.getTransaction()
            return handler.call(this, job, function (...args) {
              tx.end()
              return done.apply(this, args)
            })
          })
        }
        return process.call(this, wrappedHandler)
      }
    })
  },
  onError(err) {
    console.error('job-queue instrumentation failed', err)
  }
})

Key shim concepts used here:

  • shim.wrap(nodule, properties, wrapper) replaces a function with the one returned by wrapper(shim, original, name), keeping track of the original so it can be unwrapped.
  • shim.record(nodule, properties, recordNamer) wraps functions so each call creates a segment. The namer returns a recorder spec: name, and options such as callback (the index of the callback argument, e.g. shim.LAST), promise: true to end on promise settlement, recorder to also produce a metric from the segment, and after to run code once the call finishes. If the namer returns nothing, the original function is called without a segment.
  • The shim also provides type helpers (isFunction, isPromise, isAsyncFunction, ...), getActiveSegment(), bindSegment(), createSegment(), and unwrap().

Specialized shims add domain helpers:

Shim Notable methods
DatastoreShim setDatastore(name), recordOperation, recordQuery, recordBatchQuery, setParser, parseQuery, captureInstanceAttributes
MessageShim setLibrary(name), recordProduce, recordConsume, recordSubscribedConsume, recordPurgeQueue
WebFrameworkShim setFramework(name), setRouteParser, wrapMiddlewareMounter, recordMiddleware, recordParamware, recordRender, noticeError, setErrorPredicate, setResponsePredicate

DatastoreShim defines datastore name constants such as Cassandra, DynamoDB, ElasticSearch, Memcache, MongoDB, MySQL, Neptune, OpenSearch, Postgres, Redis, and Prisma.

The full shim API reference is generated from the source's JSDoc and published at newrelic.github.io/node-newrelic. Working example applications for each registration method live in the newrelic-node-examples repository (custom-instrumentation folder), as listed in examples/instrumentation.md.

Instrumenting a File in Your Application

To instrument one of your own modules (not in node_modules), pass its absolute path:

const path = require('node:path')

newrelic.instrument({
  moduleName: 'billing-client',
  absolutePath: path.join(__dirname, 'lib', 'billing-client.js'),
  onRequire(shim, billing) {
    shim.record(billing, 'charge', () => ({ name: 'Billing/charge', promise: true }))
  }
})

The hook watches absolutePath; moduleName remains the key used to look up the instrumentation.

ES Module Applications

For ES modules, add isEsm: true and remember that exports live on the module namespace — a default export is under .default. This example is from the README:

import newrelic from 'newrelic'

newrelic.instrument({ moduleName: 'parse-json', isEsm: true }, function wrap(shim, parseJson, moduleName) {
  shim.wrap(parseJson.default, function wrapParseJson(shim, orig) {
    return function wrappedParseJson() {
      const result = orig.apply(this, arguments)
      result.instrumented = true
      return true
    }
  })
})

The application must be started with the ESM loader: node --import newrelic/esm-loader.mjs -r newrelic app.js. See Loading the Agent.

instrumentLoadedModule (Deprecated)

newrelic.instrumentLoadedModule(moduleName, module) applies the agent's built-in instrumentation to a CommonJS module that was loaded before the agent. It returns true when instrumented. It:

  • logs a warning and emits a DeprecationWarning on every call;
  • is scheduled for removal in v15;
  • never worked for ES modules;
  • catches and logs resolution errors (instrumentLoadedModule encountered an error, module not instrumented: ...), returning false.

Replace it by loading the agent with node -r newrelic.

Tips

  • Keep segment names stable and low-cardinality (JobQueue/add, not JobQueue/add/<jobId>).
  • Use the specialized shims for databases and message brokers: they produce the metrics and attributes the APM UI expects (Databases and Message queues pages).
  • Throwing inside onRequire does not break your application: the error goes to onError if you provide it, otherwise the agent logs Custom instrumentation for <module> failed. Please report this to the maintainers of the custom instrumentation. Returning false from onRequire marks the hook as not applied.
  • Test with logging.level: 'trace' to see wrapping and segment creation in the agent log.

See Also