Tracing and Browser

This page covers the API for reading the current trace context, linking logs to traces, propagating distributed trace headers by hand, and injecting the browser monitoring script into HTML pages. For sampling and configuration, see Distributed Tracing.

getTraceMetadata()

Returns the identifiers of the current trace and span.

Returns: an object { traceId, spanId }. Keys are omitted when unknown: outside a transaction there is no traceId, and without an active segment no spanId. When distributed_tracing.enabled is false, it returns {}. (The stub API, when the agent is disabled, returns { traceId: '', spanId: '' }.)

const { traceId } = newrelic.getTraceMetadata()
res.set('x-trace-id', traceId)

The traceId is also what recordLlmFeedbackEvent expects.

getLinkingMetadata(omitSupportability)

Returns the metadata used to link log lines to traces and to the service entity ("logs in context").

Key Value
trace.id Current trace ID (only with distributed tracing enabled and an active transaction).
span.id Current span ID, when available.
entity.name The first application name.
entity.type The string SERVICE.
entity.guid The entity GUID from the connect reply.
hostname The reported host name.

Pass true to skip incrementing the Supportability/API/getLinkingMetadata metric, for example in a log formatter called on every line.

const pinoLike = (msg) => console.log(JSON.stringify({ msg, ...newrelic.getLinkingMetadata(true) }))

For supported logging libraries, application_logging.local_decorating.enabled does this for you.

Propagating Trace Context Manually

For transports the agent does not instrument (a custom TCP protocol, a message system without instrumentation), use the transaction handle from getTransaction().

On the sending side

newrelic.startBackgroundTransaction('publish', 'Queue', () => {
  const tx = newrelic.getTransaction()
  const headers = {}
  tx.insertDistributedTraceHeaders(headers)
  // headers now contains the W3C trace context headers
  // (plus "newrelic" when exclude_newrelic_header is false)
  myBus.publish({ headers, body })
  tx.end()
})

On the receiving side

myBus.subscribe((message) => {
  newrelic.startBackgroundTransaction('consume', 'Queue', () => {
    const tx = newrelic.getTransaction()
    tx.acceptDistributedTraceHeaders('Queue', message.headers)
    handle(message.body)
    tx.end()
  })
})
Method Parameters Notes
insertDistributedTraceHeaders(headers) A plain object, mutated in place. Applies the sampling decision, then writes the W3C trace context headers (traceparent, and tracestate when account data is known); writes newrelic only when distributed_tracing.exclude_newrelic_header is false. Does nothing when distributed tracing is disabled.
acceptDistributedTraceHeaders(transportType, headers) transportType defaults to 'Unknown'; header keys must be lowercase. W3C traceparent is preferred; the newrelic header is used only when no traceparent is present.

Both increment Supportability/API/Transaction/<method> metrics. Remember that calling getTransaction() means you must end the transaction yourself.

getBrowserTimingHeader(options)

Returns the browser monitoring (RUM) snippet to put in the <head> of an HTML page, as high as possible but after any X-UA-Compatible meta tags. Generate it for every response; never cache or reuse it between requests or users, because it contains the current transaction's name and timing.

Option Type Description
nonce string Adds nonce="..." to the <script> tag, for Content Security Policy.
hasToRemoveScriptWrapper boolean Return only the JavaScript, without <script> tags (for frameworks that render their own script element, such as React components).
allowTransactionlessInjection boolean Generate the snippet even when there is no active transaction. Transaction-specific fields (name, timings, attributes) are then omitted.

Returns: a string — the snippet, or an HTML comment explaining why none was generated.

app.get('/', (req, res) => {
  const rum = newrelic.getBrowserTimingHeader({ nonce: res.locals.cspNonce })
  res.send(`<!doctype html><html><head>${rum}<title>Shop</title></head><body>...</body></html>`)
})

Why the snippet can be empty

When the snippet cannot be generated, the method returns <!-- NREUM: (N) --> and logs the reason (at warn level, except code 0 which is logged at debug):

Code Logged message Typical cause
0 no browser monitoring headers generated; disabled browser_monitoring.enable is false.
1 transaction ignored while generating browser monitoring headers No active transaction (and allowTransactionlessInjection not set), or the transaction is ignored.
2 config.browser_monitoring missing, something is probably wrong Corrupt configuration.
4 browser_monitoring requires valid application_id The agent has not connected yet, or the license key is missing.
5 browser_monitoring requires valid browser_key Browser monitoring is not enabled for the app on the server.
6 browser_monitoring requires js_agent_loader script The server did not send the loader script.
7 browser_monitoring disabled by browser_monitoring.loader config The server sent loader none (browser monitoring was disabled later).

Each message is prefixed with NREUM: in the log. Code 4 is common right after startup: the browser key and loader arrive with the connect reply, so pages rendered before the agent connects have no snippet.

What the snippet contains

The script sets window.NREUM.info to a JSON object with agent, beacon, errorBeacon, licenseKey (the browser key), and applicationID, followed by the loader script. In a transaction it also includes transactionName and atts (custom and agent attributes for the browser destination), both obfuscated with the first 13 characters of your license key, plus applicationTime and queueTime. With browser_monitoring.debug: true, the JSON is pretty-printed.

Custom attributes reach the browser only if browser_monitoring.attributes.enabled is true (default false).

See Also