当前位置: 首页 > 后端技术 > Node.js

麻辣谷日志集成winston日志库

时间:2023-04-03 17:36:12 Node.js

简介本文已参与“开源摘星计划”,欢迎正在阅读的你加入。活动链接:https://github.com/weopenproj...日志是跟踪错误和事件流的首选方式。对于Serverless应用,云平台会帮我们收集日志。如果使用云平台部署,可以跳过本文。但是,如果你想部署到传统平台或者自定义收集日志,请继续……在java开发中,我们通常使用Log4j,而在前端开发中,我们通常使用console.log和debugger。但是在生产环境中,由于控制台清洁度等原因,我们无法通过console.log来跟踪错误。好在大前端有很多大牛开源了强大好用的日志库。登录node就像java中的Log4j一样简单。npm上流行的日志库Winston:灵活的通用日志库Morgan:HTTP请求记录器中间件Pino:超快(非常低的开销),纯原生JSON记录器Loglevel:JavaScript最小轻量级简单日志记录,malagu默认集成log4js:无运行时依赖的日志框架关于winstonWinston是功能强大且灵活的节点日志库之一,支持多种传输通道、自定义日志格式、日志切割、多实例等。Winston支持六级{error:0,warn:1,info:2,http:3,verbose:4,debug:5,silly:6},内置的error/warn/info可以直接写入使用levels属性方法logger.info("thisisainfo")logger.warn("thisisawarn")logger.error("thisisanerror")Winston默认有4个传输通道:Console:print到控制台File:record到文件Http:transmitStreamviahttp:通过流传输在malagu上使用,以File传输通道为例,malagu集成了winston组件,使winston在malagu上使用更方便1.引入依赖winston:日志库核心winston-daily-rotate-file:根据日期和大小限制旋转日志malagu-winston:malaguWinston组件yarnaddwinston、winston-daily-rotate-file、malagu-winston或npminstallwinston--savenpminstallwinston-daily-rotate-file--savenpm安装malagu-winston--save2。配置malagu-*.ymlmalagu:logger:winstonConfig:level:'info'//日志级别dailyRotateConfig:frequency:'24h'filename:'%DATE%.log'//日志文件名dirname:'./logs'//日志文件目录3.重写WinstonConfig组件import{Component,LOGGER_CONFIG,Value}from"@malagu/core";从&quo导入{WinstonConfig}t;malagu-winston";import{format,transports}from'winston';import*asTransportfrom'winston-transport';constDailyRotateFile=require('winston-daily-rotate-file');@组件(WinstonConfig)exportclassWinstonConfigImplimplementsWinstonConfig{transports:Transport[];constructor(//在malagu-*.yml中导入logger配置信息@Value(LOGGER_CONFIG)protectedreadonlyconfig:any,@Value('mode')protectedreadonlymode:string){const{dailyRotateConfig}=this.config;this.transports=[newDailyRotateFile({...dailyRotateConfig,//定义日志格式format:format.combine(format.timestamp({format:'YYYY-MM-DDHH:mm:ss,SSS'}),format.simple(),format.printf(msg=>`${msg.timestamp}-${msg.level}:${msg.message}`)),})];if(this.mode.includes('test')){//测试环境添加一个输出控制台通道this.transports.push(newtransports.Console({format:format.combine(format.colorize(),format.timestamp({format:'YYYY-MM-DDHH:mm:ss,SSS'}),format.simple(),format.printf(msg=>`${msg.timestamp}-${msg.level}:${msg.message}`)),}));};}}4.在module.ts中引用WinstonConfigImpl5.在文件中使用import{Autowired,Logger}from"@malagu/core";import{Controller,Get,Json,Param}from"@malagu/mvc/lib/node";从"../service"导入{UserInfoService};@Controller("user")exportclassUserController{@Autowired(Logger)protectedlogger:Logger;@Autowired(UserInfoService)protecteduserInfoService:UserInfoService;@Get("/:userId")@Json()@Authenticated()asyncgetUserInfo(@Param("userId")userId:number){this.logger.info(`获取用户信息:${userId}`)const结果=等待this.userInfoService.getUserInfo(userId);返回结果}}日志输出位置日志内容2022-08-1013:42:42,802-信息:GET/api/user/100000(在LAPTOP-EU7RHVSK上为53092)开始GET/api/user/100000withtraceId[08bfe038-47b4-4357-b8fe-a51b7618b8c2]2022-08-1013:42:42,864-信息:GET/api/user/100000(在LAPTOP-EU7RHVSK上为53092)与08bfe038-57b4-83a51b7618b8c2获取用户信息:1000008-02022-13:42:42,966-信息:GET/api/user/100000(在LAPTOP-EU7RHVSK上为53092)带有08bfe038-47b4-4357-b8fe-a51b7618b8c2/00结束GET/带有traceId[08bfe038-47b4-4357-b8fe-a51bc2618],cost162ms结论winston在malagu的应用还是比较好用的。winston的更多使用可以参考乔克利的《Node.js日志神器(winston)》关于在yml中实现多级日志输出的思考如何配置?如果不使用malagu-winston组件,如何实现这一点?本文为学习文章,如有错误请指正!思考内容欢迎大家回答问题