寻求NestJS中已废弃newrelic-winston包的替代方案
替代方案推荐
方案一:使用New Relic官方Winston传输器(推荐)
New Relic官方维护了@newrelic/winston-transport包,专门用于对接Winston日志上报,是废弃包的官方替代方案,兼容性和稳定性更有保障。
操作步骤:
- 安装依赖
npm install @newrelic/winston-transport
- 修改原有代码替换废弃组件:
import * as winston from 'winston'; import { WinstonModule } from 'nest-winston'; import { utilities as nestWinstonModuleUtilities } from 'nest-winston/dist/winston.utilities'; import { NewRelicTransport } from '@newrelic/winston-transport'; const configs = { format: winston.format.combine( winston.format.timestamp(), nestWinstonModuleUtilities.format.nestLike(), ), }; const app = await NestFactory.create(AppModule, { logger: WinstonModule.createLogger({ transports: [ new winston.transports.Console(configs), new NewRelicTransport({ level: 'info', // 可指定上报的日志级别 serviceName: 'your-nestjs-service' // 可自定义服务名,默认读取newrelic配置 }), ], }), });
注意:确保项目已正确配置New Relic客户端(安装
newrelic包并创建newrelic.js配置文件),官方传输器会自动读取这些配置。
方案二:自定义Winston传输器
如果需要更灵活的日志字段控制,可以自行实现Winston传输器,直接调用New Relic的日志API上报。
自定义传输器示例:
import * as winston from 'winston'; import newrelic from 'newrelic'; class CustomNewRelicTransport extends winston.Transport { constructor(opts: winston.transport.TransportStreamOptions) { super(opts); } log(info: any, callback: () => void) { // 调用New Relic API上报日志事件 newrelic.recordLogEvent({ message: info.message, level: info.level, timestamp: info.timestamp, // 可添加自定义业务字段,如请求ID、用户ID等 ...info }); callback(); } }
在NestJS中使用:
const app = await NestFactory.create(AppModule, { logger: WinstonModule.createLogger({ transports: [ new winston.transports.Console(configs), new CustomNewRelicTransport({ level: 'info' }), ], }), });
方案三:使用日志转发代理
若不想修改代码,可通过New Relic日志转发代理(如newrelic-log-forwarder)收集日志。只需配置Winston将日志输出到文件,再由代理自动读取文件并上报到New Relic。
简要操作:
- 安装代理依赖
npm install newrelic-log-forwarder
- 配置代理指向Winston输出的日志文件路径,启动代理后即可自动完成日志上报。
内容的提问来源于stack exchange,提问作者Armen
相关产品推荐
相关产品推荐

