这些库涵盖了 JavaScript 应用(包括 Node.js 后端和浏览器前端)的可观测性核心领域:应用性能监控 (APM)、错误追踪、指标收集和日志管理。sentry 和 raygun 专注于错误监控且支持浏览器端;newrelic 和 elastic-apm-node 提供全栈 APM 解决方案;prom-client 和 datadog-metrics 专注于指标暴露;loggly 用于日志聚合;而 opentracing 是分布式追踪的规范接口(现已逐步被 OpenTelemetry 取代)。选择合适的工具取决于你需要监控的层面(前端/后端)以及你现有的基础设施(如是否使用 Kubernetes、Datadog 平台等)。
在构建现代 Web 应用时,了解系统运行状态至关重要。我们对比了 8 款主流的可观测性 npm 包,涵盖了从错误追踪到性能指标的全方位监控。这些工具在架构定位、支持环境(前端/后端)以及数据收集方式上有显著差异。
这是前端架构师最需要关注的区别。部分工具专为服务器设计,而部分则能直接运行在用户浏览器中。
sentry 和 raygun 是少数原生支持浏览器的错误监控工具。
// sentry: 支持浏览器和 Node.js
import * as Sentry from "@sentry/browser";
Sentry.init({ dsn: "https://...@sentry.io/..." });
// raygun: 支持浏览器 (raygun4js)
import Raygun from 'raygun4js';
Raygun('apiKey').attach();
elastic-apm-node, newrelic, prom-client, datadog-metrics, loggly 主要设计用于 Node.js 后端环境。
// elastic-apm-node: 仅 Node.js
const apm = require('elastic-apm-node').start({ serviceName: 'my-app' });
// newrelic: 仅 Node.js (通常作为第一个 require)
require('newrelic');
// prom-client: 仅 Node.js
const client = require('prom-client');
const collectDefaultMetrics = client.collectDefaultMetrics;
collectDefaultMetrics();
// datadog-metrics: 仅 Node.js
const metrics = require('datadog-metrics');
metrics.init({ apiKey: '...' });
// loggly: 仅 Node.js
const loggly = require('loggly');
const client = loggly.createClient({ token: '...' });
opentracing 是一个规范接口,本身不区分环境,但具体实现通常依赖后端。
// opentracing: 规范接口 (已归档,建议迁移至 OpenTelemetry)
const opentracing = require('opentracing');
const tracer = new opentracing.Tracer();
当用户遇到崩溃时,谁能第一时间通知你?
sentry 和 raygun 专注于错误捕获,能自动捕获未处理的异常,并允许手动报告。
// sentry: 自动捕获 + 手动上下文
try { doSomething(); }
catch (e) { Sentry.captureException(e); }
// raygun: 手动发送错误
raygunClient.send(new Error('Something broke'), { tags: ['critical'] });
newrelic 和 elastic-apm-node 作为 APM 工具,也会记录错误,但更侧重于错误与事务(Transaction)的关联。
// newrelic: 自动捕获,也可手动通知
const newrelic = require('newrelic');
newrelic.noticeError(new Error('DB failed'));
// elastic-apm-node: 手动捕获异常
apm.captureError(new Error('API timeout'));
prom-client, datadog-metrics, loggly, opentracing 不直接提供“错误追踪”界面,它们记录的是指标或日志。
// prom-client: 通过指标间接反映错误 (如增加错误计数器)
const errors = new client.Counter({ name: 'app_errors_total' });
errors.inc();
// loggly: 发送错误日志
client.log('error', { message: 'Failed to load', stack: e.stack });
// datadog-metrics: 记录错误指标
metrics.increment('app.errors');
// opentracing: 在 Span 中标记错误
span.setTag('error', true);
span.log({ event: 'error', 'error.object': e });
了解应用的性能瓶颈和业务吞吐量。
prom-client 是 Prometheus 生态的标准,适合自定义业务指标。
// prom-client: 定义直方图监控响应时间
const duration = new client.Histogram({
name: 'http_request_duration_seconds',
help: 'Duration of HTTP requests in seconds'
});
duration.observe(responseTime);
datadog-metrics 适合直接推送到 Datadog 平台。
// datadog-metrics: 直接发送 Gauge 或 Count
metrics.gauge('my.app.memory_usage', process.memoryUsage().rss);
metrics.increment('my.app.requests');
newrelic 和 elastic-apm-node 会自动收集系统指标(CPU, 内存),也支持自定义。
// newrelic: 自定义指标
newrelic.recordMetric('Custom/UserSignups', 1);
// elastic-apm-node: 自定义标签
apm.setLabel('userId', 123);
sentry, raygun, loggly, opentracing 主要不是为指标设计的,虽然 Sentry 有 Performance 功能,但 prom-client 更专业。
// sentry: 性能事务 (Transactions)
const transaction = Sentry.startTransaction({ name: 'load-dashboard' });
// ... do work ...
transaction.finish();
// raygun: 主要是错误,指标功能有限
// 无直接指标 API
// loggly: 日志即数据,需后续分析
// 无直接指标 API
// opentracing: 追踪耗时
const span = tracer.startSpan('db-query');
span.finish();
loggly 是纯粹的日志聚合服务客户端。
// loggly: 发送结构化日志
client.log({ level: 'info', event: 'user_login', id: 456 });
opentracing 用于分布式链路追踪,解决微服务间的调用链问题。
// opentracing: 创建追踪 Span
const span = tracer.startSpan('process-order');
// 传递 context 到下游服务
tracer.inject(span.context(), opentracing.FORMAT_HTTP_HEADERS, headers);
elastic-apm-node 和 newrelic 内置了分布式追踪能力,无需手动管理 Span。
// elastic-apm-node: 自动追踪 HTTP 请求
// 无需额外代码,Agent 自动拦截 http 模块
// newrelic: 自动追踪
// Agent 自动注入追踪头
在选择技术栈时,了解项目的活跃度至关重要。
opentracing: 该项目已与 OpenCensus 合并为 OpenTelemetry。官方建议新项目直接使用 @opentelemetry/api 和 @opentelemetry/sdk。opentracing 包已进入维护模式,不再推荐用于新架构。loggly: 虽然仍可用,但现代开发更倾向于将日志输出到标准输出 (stdout),由基础设施层(如 Fluentd, Datadog Agent)统一收集,减少应用耦合。sentry: 目前前端错误监控的事实标准,更新频繁,生态最完善。prom-client: Kubernetes 环境下的标准配置,非常稳定。| 特性 | sentry | newrelic | elastic-apm-node | prom-client | datadog-metrics | raygun | loggly | opentracing |
|---|---|---|---|---|---|---|---|---|
| 主要用途 | 错误 & 性能 | 全栈 APM | 全栈 APM | 指标暴露 | 指标推送 | 错误监控 | 日志聚合 | 追踪规范 |
| 浏览器支持 | ✅ 优秀 | ❌ (需配合 RUM) | ❌ (需配合 RUM) | ❌ | ❌ | ✅ 支持 | ❌ | ❌ |
| Node.js 支持 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| 自动探针 | ⚠️ 部分 | ✅ 强大 | ✅ 强大 | ❌ | ❌ | ⚠️ 部分 | ❌ | ❌ |
| 开源/闭源 | 开源核心 | 闭源 SaaS | 开源 + SaaS | 开源 | 闭源 SaaS | 闭源 SaaS | 闭源 SaaS | 开源规范 |
| 推荐场景 | 全栈错误追踪 | 企业级监控 | ELK 栈用户 | K8s/Prometheus | Datadog 用户 | 轻量错误监控 | 日志归档 | 旧版微服务 |
对于前端架构师:
sentry:它对前端框架(React, Vue, Angular)的支持最好,能捕获源码映射后的错误,且提供优秀的用户反馈界面。raygun 是备选,但生态略小。prom-client 和 datadog-metrics 是给 Node.js 服务用的,不要试图把它们打包进前端代码。opentracing,直接研究 OpenTelemetry,它是未来的标准。prom-client + Grafana 是标配。如果公司买了 Datadog 或 New Relic,直接用对应的 Agent 最省事。总结:没有唯一的最佳工具,只有最适合你架构的组合。通常的最佳实践是:前端用 Sentry,后端用 Prometheus (指标) + ELK/NewRelic (日志与追踪)。
如果你希望获得开箱即用的全栈性能监控(包括数据库查询、外部 API 调用等)且预算充足,New Relic 提供非常详细的自动探针。主要用于 Node.js 后端。
如果你已经在使用 Datadog 平台且只需要在 Node.js 服务中发送自定义指标(如业务计数器),选择此包。注意它主要用于后端,不支持浏览器端直接发送。
如果你的基础设施基于 ELK 栈 (Elasticsearch, Logstash, Kibana) 且需要自动化的分布式追踪和性能监控,这是 Node.js 后端的首选。它不适合直接运行在浏览器中。
如果你需要一个简单的日志传输客户端将 Node.js 日志发送到 Loggly 云端进行分析,可以选择它。但在现代架构中,通常更倾向于使用标准的 stdout 配合日志收集器。
如果你需要构建与供应商无关的追踪代码,可以使用此规范库。但请注意,OpenTracing 项目已合并至 OpenTelemetry,新项目建议直接使用 OpenTelemetry 而非此包。
如果你的应用部署在 Kubernetes 环境中并使用 Prometheus 进行监控,这是 Node.js 应用暴露指标的标准库。它只负责收集指标,不负责存储或报警。
如果你需要一个轻量级的错误监控方案,且特别关注浏览器端的 JavaScript 错误捕获和用户会话回放,Raygun 是一个不错的 SaaS 选择。
如果你需要业界领先的错误追踪方案,且同时覆盖前端(React/Vue 等)和后端(Node.js/Python 等),Sentry 是最佳选择。它的上下文信息最丰富,集成最简单。
This package instruments your application for performance monitoring with New Relic.
In order to take full advantage of this package, make sure you have a New Relic account before starting.
As with any instrumentation tool, please test before using in production.
To use New Relic's Node.js agent entails these three steps, which are described in detail below:
newrelic packageTo install the agent for performance monitoring, use your favorite npm-based package manager and install the newrelic package into your application:
$ npm install newrelic
Then, copy the stock configuration file to your program's base folder:
$ cp ./node_modules/newrelic/newrelic.js ./<your destination>
Now, add your New Relic license key and application/service name to that file:
/* File: newrelic.js */
'use strict'
/**
* New Relic agent configuration.
*
* See lib/config/default.js in the agent distribution for a more complete
* description of configuration variables and their potential values.
*/
exports.config = {
app_name: ['Your application or service name'],
license_key: 'your new relic license key',
/* ... rest of configuration .. */
}
Finally, run your program with the newrelic module loaded first by using node's -r/--require flag.
$ node -r newrelic your-program.js
If you cannot control how your program is run, you can load the newrelic module before any other module in your program.
const newrelic = require('newrelic')
/* ... the rest of your program ... */
We recommend using the hybrid agent functionality to setup Next.js. Please read our Next.js instrumentation with hybrid agent document for more information. The following example applications show how to load the newrelic hybrid agent instrumentation, inject browser agent, and deploying to Vercel:
If your application is written with import and export statements in javascript, you are using ES Modules and must bootstrap the agent in a different way.
The New Relic Node.js agent includes support for ES Modules.
If you rely on a configuration file to run the agent, you must rename the file from newrelic.js to newrelic.cjs so it can be properly loaded. All the contents of the configuration file will behave the same once you rename. See CommonJS modules in ESM for more details.
$ mv newrelic.js newrelic.cjs
To use the newrelic ESM loader, start your program with node and use the --import flag and a path to the loader file, like this:
$ node --import newrelic/esm-loader.mjs -r newrelic your-program.js
The agent supports adding your own custom instrumentation to ES module applications. You can use the instrumentation API methods. The only other difference between CommonJS custom instrumentation and ESM is you must provide a property of isEsm: true.
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
}
})
})
We support the following custom instrumentation API methods in ES module apps:
newrelic.instrumentnewrelic.instrumentConglomeratenewrelic.instrumentDatastorenewrelic.instrumentMessagesnewrelic.instrumentWebframeworkNote that newrelic.instrumentLoadedModule is deprecated and scheduled for removal in v15. It was never supported in ES module apps, and in CommonJS it only existed to retrofit instrumentation when the agent was loaded after user modules, which is no longer supported.
If you want to see an example of how to write custom instrumentation in an ES module app, check out our examples repo for a working demo.
For more information on getting started, check the Node.js docs.
There are modules that can be installed and configured to accompany the Node.js agent:
@newrelic/native-metrics: Provides hooks into the native v8 layer of Node.js to provide metrics to the Node.js agent.The newrelic module returns an object with the Node.js agent's API methods attached.
const newrelic = require('newrelic')
/* ... */
newrelic.addCustomAttribute('some-attribute', 'some-value')
You can read more about using the API over on the New Relic documentation site.
These are the steps to work on core agent features, with more detail below:
npmFork and clone this GitHub repository:
$ git clone git@github.com:your-user-name/node-newrelic.git
$ cd node-newrelic
Install the project's dependencies:
$ npm install
Then you're all set to start programming.
$ npm run services$ npm run testAvailable test suites include:
$ npm run unit
$ npm run integration
$ npm run versioned
$ npm run lint
$ npm run smoke
Here are some resources for learning more about the agent:
Configuring the agent using newrelic.js or environment variables
Example applications - Working examples of New Relic features in Node.js.
Should you need assistance with New Relic products, you are in good hands with several support channels.
If the issue has been confirmed as a bug or is a feature request, please file a GitHub issue.
Support Channels
At New Relic we take your privacy and the security of your information seriously, and are committed to protecting your information. We must emphasize the importance of not sharing personal data in public forums, and ask all users to scrub logs and diagnostic information for sensitive information, whether personal, proprietary, or otherwise.
We define “Personal Data” as any information relating to an identified or identifiable individual, including, for example, your name, phone number, post code or zip code, Device ID, IP address and email address.
Please review New Relic’s General Data Privacy Notice for more information.
We encourage your contributions to improve the Node.js agent! Keep in mind when you submit your pull request, you'll need to sign the CLA via the click-through using CLA-Assistant. You only have to sign the CLA one time per project.
If you have any questions, or to execute our corporate CLA, required if your contribution is on behalf of a company, please drop us an email at opensource@newrelic.com.
A note about vulnerabilities
As noted in our security policy, New Relic is committed to the privacy and security of our customers and their data. We believe that providing coordinated disclosure by security researchers and engaging with the security community are important means to achieve our security goals.
If you believe you have found a security vulnerability in this project or any of New Relic's products or websites, we welcome and greatly appreciate you reporting it to New Relic through our bug bounty program.
If you would like to contribute to this project, review these guidelines.
To all contributors, we thank you! Without your contribution, this project would not be what it is today.
Except as noted below, the Node.js agent is licensed under the Apache 2.0 License.
The New Relic security agent is licensed under the New Relic Software License v1.0. The New Relic security agent module may be integrated like the New Relic Node.js agent.
The Node.js agent also uses source code from third-party libraries. You can find full details on which libraries are used and the terms under which they are licensed in the third-party notices document.