Newrelic与私有Node.js npm包集成:独立实现库的可观测性
如何在私有NPM库中独立集成New Relic实现可观测性
要让私有NPM库不依附父HTTP应用,独立实现New Relic可观测性,需要手动初始化New Relic并管理追踪事务,以下是具体步骤:
1. 安装New Relic依赖
在你的库项目中安装官方New Relic Node.js代理:
npm install newrelic # 或者用yarn yarn add newrelic
2. 创建New Relic配置文件
在库的根目录新建newrelic.js配置文件,配置核心参数并支持环境变量注入(避免硬编码敏感信息):
'use strict' exports.config = { // 应用名称,优先读取环境变量 app_name: [process.env.NEW_RELIC_APP_NAME || 'private-npm-library'], // License Key,必须通过环境变量传入,确保安全 license_key: process.env.NEW_RELIC_LICENSE_KEY, logging: { level: process.env.NEW_RELIC_LOG_LEVEL || 'info' }, // 开启分布式追踪,支持跨服务链路追踪(如果你的库调用其他服务) distributed_tracing: { enabled: true }, // 允许库作为独立实体上报数据 allow_all_headers: true, // 过滤敏感属性,避免上报敏感数据 attributes: { exclude: [ 'request.headers.cookie', 'request.headers.authorization', 'response.headers.cookie', 'response.headers.authorization' ] } }
3. 在库入口初始化New Relic
必须将New Relic的引入放在库所有代码的最顶部,确保代理能捕获所有操作。然后手动管理事务、事件和指标:
// 放在文件最开头,初始化New Relic const newrelic = require('newrelic'); const packageInfo = require('./package.json'); class MyPrivateLibrary { constructor() { // 记录库初始化的自定义事件 newrelic.recordCustomEvent('LibraryInit', { version: packageInfo.version, timestamp: Date.now() }); } async coreBusinessMethod(inputData) { // 手动启动自定义事务,指定事务名称和类型 const transaction = newrelic.startTransaction( 'coreBusinessMethod', 'library-operation' ); try { // 给事务添加自定义属性,方便后续排查 newrelic.addCustomAttribute('inputData', JSON.stringify(inputData)); // 你的核心业务逻辑 const result = await this.processData(inputData); // 记录成功指标 newrelic.recordMetric('Library/coreBusinessMethod/Success', 1); return result; } catch (err) { // 上报错误到New Relic newrelic.noticeError(err); // 记录失败指标 newrelic.recordMetric('Library/coreBusinessMethod/Failure', 1); throw err; } finally { // 手动结束事务,确保数据上报 transaction.end(); } } async processData(data) { // 可以在这里给子操作添加自定义片段追踪 const segment = newrelic.startSegment('processData', false, () => {}); try { // 子业务逻辑 return await someAsyncTask(data); } finally { segment.end(); } } } module.exports = MyPrivateLibrary;
4. 指导使用方配置环境变量
使用你的库的应用,需要在运行时设置以下环境变量,确保New Relic能正确上报数据:
# Linux/macOS export NEW_RELIC_LICENSE_KEY="你的New Relic License Key" export NEW_RELIC_APP_NAME="你的库的上报应用名称" # Windows(PowerShell) $env:NEW_RELIC_LICENSE_KEY="你的New Relic License Key" $env:NEW_RELIC_APP_NAME="你的库的上报应用名称"
5. 验证可观测性数据
运行使用该库的代码后,登录New Relic控制台:
- 在Transactions页面可以看到
library-operation类型的自定义事务 - 在Events页面可以找到
LibraryInit自定义事件 - 在Metrics页面可以查看
Library/coreBusinessMethod/*系列指标
关键注意事项
- 永远不要在库中硬编码
license_key,必须通过环境变量由使用方配置 - 所有自定义事务都需要手动调用
startTransaction和end,New Relic不会自动捕获非HTTP触发的操作 - 可以根据库的功能,添加更多自定义事件、指标和属性,细化可观测维度
内容的提问来源于stack exchange,提问作者Arjun Londhey
相关产品推荐
相关产品推荐

