Errors and Logs
The agent collects uncaught errors and HTTP error responses automatically. This page covers the API for reporting errors you handle yourself, grouping errors in Errors Inbox, and sending log records, plus the configuration that controls which errors count.
noticeError(error, customAttributes, expected)setErrorGroupCallback(callback)recordLogEvent(logEvent)- How errors are filtered
- Application logging
noticeError(error, customAttributes, expected)
Reports an error that your code caught and handled, so it still shows up in New Relic.
| Parameter | Type | Description |
|---|---|---|
error |
Error or string | The error. A string is wrapped in new Error(string). Objects with message or stack are also accepted. |
customAttributes |
object | Optional. Attributes attached to the error. Only string, number, and boolean values are kept. |
expected |
boolean | Optional, default false. An expected error is collected but does not count toward the error rate. |
Returns: false when api.notice_error_enabled is false, otherwise undefined.
try {
await chargeCard(order)
} catch (err) {
newrelic.noticeError(err, { orderId: order.id, gateway: 'stripe' })
res.status(402).send('Payment failed')
}
// Expected business error: tracked, but not part of the error rate
newrelic.noticeError(new Error('Coupon expired'), { coupon: code }, true)
// You can skip the attributes and pass `expected` second
newrelic.noticeError(validationError, true)
Behavior details:
- Inside a transaction, the error is attached to it and reported when the transaction ends. Outside a transaction it is collected immediately, without request details.
error_collector.ignore_status_codesdoes not apply to errors reported withnoticeError.- If
error_collector.enabledisfalse, the error is dropped. - Custom attributes are dropped when
high_securityistrueorapi.custom_attributes_enabledisfalse, and must also pass theerror_collector.attributesfilters. - With
high_securityorstrip_exception_messages.enabled, the message is redacted: the first stack line becomes<ErrorName>: <redacted>.
setErrorGroupCallback(callback)
Registers a function that computes the error.group.name attribute, which Errors Inbox uses to group similar errors. Calling it again replaces the previous callback.
The callback must be synchronous (an async function is rejected with Error Group callback must be a synchronous function, Error Group attribute will not be added). It receives one object:
| Key | Type | Description |
|---|---|---|
error |
Error | The error object. |
customAttributes |
object | Custom attributes attached to the error. |
request.uri |
string | The request URI, if in a web transaction. |
http.statusCode |
string | The response status code. |
http.method |
string | The request method. |
error.expected |
boolean | Whether the error is expected. |
It must return a non-empty string. Any other return value logs Function provided via setErrorGroupCallback return value malformed; a thrown exception logs Function provided via setErrorGroupCallback failed, not generating error.group.name. In both cases the error is still reported, just without a group name.
newrelic.setErrorGroupCallback((meta) => {
if (meta['http.statusCode'] === '400') return 'Bad User Input'
if (meta.error?.code === 'ECONNRESET') return 'Upstream connection reset'
// returning undefined leaves the error ungrouped
})
recordLogEvent(logEvent)
Sends one log record to New Relic. Use it for logging libraries the agent does not instrument; supported libraries (such as winston, pino, and bunyan) are forwarded automatically.
| Field | Type | Description |
|---|---|---|
message |
string | Required. The log message. |
level |
string | Severity. Defaults to UNKNOWN. |
timestamp |
number | Epoch milliseconds. Defaults to Date.now() when not a number. |
error |
Error | Optional. Converted to error.message, error.stack, and error.class. |
| any other key | — | Sent unchanged as an attribute. |
newrelic.recordLogEvent({
message: 'cannot find file',
level: 'ERROR',
error: new Error('missing.txt'),
component: 'importer'
})
Behavior details:
- Does nothing unless both
application_logging.enabledandapplication_logging.forwarding.enabledaretrue(logged once:Application log forwarding disabled, method API#recordLogEvent will not record messages). High security mode forces forwarding off. - A missing
messagelogsrecordLogEvent requires an object with a `message` attribute ...and drops the record. - The object you pass is mutated:
levelandtimestampare filled in, theerrorkey is deleted and replaced by theerror.*fields. Pass a copy if you reuse it. error.messageanderror.stackare truncated to 1021 characters plus....error.classis the error'sname, or its constructor name whennameis the genericError.- Linking metadata (
trace.id,span.id,entity.name,entity.guid,hostname, ...) is added so the record appears in logs-in-context. - When
application_logging.metrics.enabledistrue, the record also increments the logging line metrics for its level.
How Errors Are Filtered
The error_collector settings decide what is reported and what counts toward the error rate:
| Setting | Effect |
|---|---|
error_collector.enabled |
Master switch for error collection (instrumentation stays loaded). |
error_collector.ignore_status_codes |
HTTP status codes that are not errors. Default [404]. |
error_collector.expected_status_codes |
Status codes reported as expected errors. |
error_collector.ignore_classes |
Error class names never reported. |
error_collector.expected_classes |
Error class names reported as expected. |
error_collector.ignore_messages |
{ "<ErrorClass>": ["<exact message>", ...] } never reported. |
error_collector.expected_messages |
{ "<ErrorClass>": ["<exact message>", ...] } reported as expected. |
error_collector.capture_events |
Whether error events are sent. |
error_collector.max_event_samples_stored |
Error events kept per harvest (default 100). |
Status code lists accept numbers and range strings such as "400-421" (bounds between 0 and 1000, lower bound first); invalid entries log Failed to parse status code ... or a Range must ... warning. Message matching is exact (whole message, case-sensitive).
exports.config = {
error_collector: {
ignore_status_codes: [404, '405-410'],
expected_classes: ['ValidationError'],
ignore_messages: { Error: ['socket hang up'] }
}
}
Environment variable forms: NEW_RELIC_ERROR_COLLECTOR_IGNORE_ERROR_CODES=404,401, NEW_RELIC_ERROR_COLLECTOR_EXPECTED_ERRORS=ValidationError, and JSON for messages: NEW_RELIC_ERROR_COLLECTOR_IGNORE_MESSAGES='{"Error":["socket hang up"]}'.
gRPC servers have their own grpc.record_errors and grpc.ignore_status_codes.
Application Logging
For instrumented logging libraries, three independent features are controlled by application_logging:
| Feature | Setting | Default | What it does |
|---|---|---|---|
| Forwarding | application_logging.forwarding.enabled |
true |
Sends log records to New Relic (up to max_samples_stored, default 10000, per harvest). |
| Metrics | application_logging.metrics.enabled |
true |
Counts log lines per level as metrics. |
| Local decorating | application_logging.local_decorating.enabled |
false |
Adds linking metadata to your own log output, for use with a separate log shipper. |
application_logging.enabled: false turns all three off. With forwarding.labels.enabled: true, your labels are attached to forwarded records, except those listed in forwarding.labels.exclude (case-insensitive).