关于typescript:malagu日志之集成winston日志库

3次阅读

共计 3381 个字符,预计需要花费 9 分钟才能阅读完成。

导言

  • 本文已参加「开源摘星打算」,欢送正在浏览的你退出。流动链接: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  
    
      }
    
    }
    

    日志输入地位

    日志内容

    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 组件,该如何实现?

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

正文完
 0