likes
comments
collection
share

malagu日志之集成winston日志库

作者站长头像
站长
· 阅读数 25

导言

  • 本文已参与「开源摘星计划」,欢迎正在阅读的你加入。活动链接: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 :没有运行时依赖的日志框架

关于winston

winston是强大灵活的node日志库之一,支持多种传输通道,自定义日志格式,日志切割,多实例等。winston支持六种级别{error: 0, warn: 1, info: 2, http: 3, verbose: 4, debug: 5, silly: 6},内置error/warn/info可以直接使用levels属性方法写入日志

logger.info("this is a info")

logger.warn("this is a warn")

logger.error("this is a error")

winston 默认有 4 种传输通道:Console:打印到控制台File:记录到文件中Http:通过 http 传输Stream:通过流传输

在malagu上使用,以File传输通道为例

malagu集成有winston组件,使得winston在malagu上使用更加简便

  • 1.引入依赖winston:日志库核心winston-daily-rotate-file:根据日期、大小限制轮换日志malagu-winston:malagu Winston组件

    yarn add winston,winston-daily-rotate-file,malagu-winston
    或者
    npm install winston --save
    npm install winston-daily-rotate-file --save
    npm install malagu-winston --save
  • 2.配置malagu-*.yml

    malagu:
      logger:
          winstonConfig:
              level: 'info' //日志级别
          dailyRotateConfig:
              frequency: '24h'
              filename: '%DATE%.log' //日志文件名
              dirname: './logs' //日志文件目录
  • 3.重写WinstonConfig组件

    import { Component, LOGGER_CONFIG, Value } from "@malagu/core";
    import { WinstonConfig } from "malagu-winston";
    import { format, transports } from 'winston';
    import * as Transport from 'winston-transport';
    const DailyRotateFile = require('winston-daily-rotate-file');
    
    @Component(WinstonConfig)
    export class WinstonConfigImpl implements WinstonConfig{
      transports: Transport[];
      constructor(
          // 引入malagu-*.yml中logger配置信息
          @Value(LOGGER_CONFIG)
          protected readonly config: any,
          @Value('mode')
          protected readonly mode: string
        ) {
          const { dailyRotateConfig } = this.config;
          this.transports = [
            new DailyRotateFile({
              ...dailyRotateConfig,
              // 定义日志格式
              format: format.combine(
                format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss,SSS'}),
                format.simple(),
                format.printf(msg =>
                  `${msg.timestamp} - ${msg.level}: ${msg.message}`
                )
              ),
            })
          ];
          if (this.mode.includes('test')) {
            // 测试环境增加输出控制台通道
            this.transports.push(new transports.Console({
              format: format.combine(
                format.colorize(),
                format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss,SSS'}),
                format.simple(),
                format.printf(msg =>
                  `${msg.timestamp} - ${msg.level}: ${msg.message}`
                )
              ),
            }));
          };
        }
      
    }
  • 4.在module.ts中引用WinstonConfigImpl
  • 5.在文件中使用

    import { Autowired, Logger } from "@malagu/core";
    import { Controller, Get, Json, Param } from "@malagu/mvc/lib/node";
    import { UserInfoService } from "../service";
    
    @Controller("user")
    export class UserController {
      @Autowired(Logger)
      protected logger: Logger;
    
      @Autowired(UserInfoService)
      protected userInfoService: UserInfoService;
    
      @Get("/:userId")
      @Json()
      @Authenticated()
      async getUserInfo(@Param("userId") userId: number){
          this.logger.info(`获取用户信息:${userId}`)
          const result = await this.userInfoService.getUserInfo(userId);     
          return result  
    
      }
    
    }
    

    日志输出位置malagu日志之集成winston日志库日志内容

    2022-08-10 13:42:42,802 - info: GET /api/user/100000 ( 53092 on LAPTOP-EU7RHVSK) starting GET /api/user/100000 with traceId[08bfe038-47b4-4357-b8fe-a51b7618b8c2]
    2022-08-10 13:42:42,864 - info: GET /api/user/100000 ( 53092 on LAPTOP-EU7RHVSK) with 08bfe038-47b4-4357-b8fe-a51b7618b8c2 获取用户信息:100000
    2022-08-10 13:42:42,966 - info: GET /api/user/100000 ( 53092 on LAPTOP-EU7RHVSK) with 08bfe038-47b4-4357-b8fe-a51b7618b8c2 ending GET /api/user/100000 with traceId[08bfe038-47b4-4357-b8fe-a51b7618b8c2], cost 162ms
    

结语

winston在malagu中的应用还是比较容易上手的,更多winston的使用请参考的乔珂力的《Node.js日志神器(winston)》

思考

  • 实现多级别日志输出在yml中怎么配置?
  • 如果不使用malagu-winston组件,该如何实现?

本文为学习类文章,如有错误欢迎指正!思考内容欢迎各位大佬答疑解惑。