NestJS日志无法转发至New Relic?配置后无日志显示排查
NestJS应用New Relic日志未显示问题排查方案
1. 确保New Relic Agent优先加载
NestJS启动时必须保证New Relic Agent在所有业务代码前初始化,否则日志关联逻辑会失效:
- 启动命令改为:
node -r newrelic dist/main.js(假设编译后文件在dist目录) - 或者在
main.ts最顶部添加:
import 'newrelic';
2. 修复Winston格式化配置
当前printf规则丢弃了@newrelic/winston-enricher添加的元数据,导致New Relic无法识别日志关联信息,以下两种方案二选一:
方案A:保留文本格式并附加元数据
import * as winston from 'winston'; const newrelicFormatter = require('@newrelic/winston-enricher'); const newrelicWinstonFormatter = newrelicFormatter(winston); const logger = winston.createLogger({ format: winston.format.combine( winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), newrelicWinstonFormatter(), // 移除colorize避免ANSI转义字符干扰解析 winston.format.printf(({ level, timestamp, message, newrelic }) => { const nrMetadata = newrelic ? ` | ${JSON.stringify(newrelic)}` : ''; return `${timestamp} [${level}] - ${message}${nrMetadata}`; }) ), transports: [new winston.transports.Console()], });
方案B:改用JSON格式输出(推荐,解析更可靠)
import * as winston from 'winston'; const newrelicFormatter = require('@newrelic/winston-enricher'); const newrelicWinstonFormatter = newrelicFormatter(winston); const logger = winston.createLogger({ format: winston.format.combine( winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), newrelicWinstonFormatter(), winston.format.json() // JSON格式能让New Relic直接识别元数据 ), transports: [new winston.transports.Console()], });
3. 完善New Relic配置
补充日志关联相关配置项,修改newrelic.js:
exports.config = { app_name: ['appName'], license_key: 'KEY', logging: { level: 'info', filepath: 'stdout', }, allow_all_headers: true, attributes: { custom_key: 'custom_value', }, error_collector: { enabled: true, }, transaction_tracer: { enabled: true, }, application_logging: { forwarding: { enabled: true, max_samples_stored: 10000 }, // 开启本地日志装饰,确保日志关联到对应事务 local_decorating: { enabled: true } }, browser_monitoring: { enable: true, }, };
4. 验证依赖兼容性
确保@newrelic/winston-enricher与newrelic Agent版本匹配,执行以下命令检查并更新:
npm list newrelic @newrelic/winston-enricher # 版本不兼容时重新安装最新版 npm install newrelic@latest @newrelic/winston-enricher@latest
5. 测试验证
启动应用后触发业务日志(如接口请求、自定义日志输出),等待3-5分钟后查看New Relic控制台的Logs板块,日志存在一定延迟属正常情况。
内容的提问来源于stack exchange,提问作者John Oliver
相关产品推荐
相关产品推荐

