Nest.js 整合 Winston 日志系统的实战教程

初步集成

创建项目:

bash 复制代码
nest new nest-winston-test -p npm

进入目录将服务跑起来:

bash 复制代码
npm run start:dev

安装 winston:

bash 复制代码
npm install winston

创建 logger.service.ts:

typescript 复制代码
import { Injectable, LoggerService } from '@nestjs/common';
import * as winston from 'winston';

@Injectable()
export class WinstonLoggerService implements LoggerService {
  private readonly logger: winston.Logger;

  constructor() {
    this.logger = winston.createLogger({
      transports: [
        new winston.transports.Console(),
        // 根据需要添加更多的 transports
      ],
      format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.printf(
          (info) => `${info.timestamp} ${info.level}: ${info.message}`,
        ),
      ),
    });
  }

  log(message: string) {
    this.logger.log('info', message);
  }

  error(message: string, trace: string) {
    this.logger.log('error', `${message} - ${trace}`);
  }

  warn(message: string) {
    this.logger.log('warn', message);
  }

  // 根据需要添加更多的日志级别方法
}

注册:

使用:

访问下 localhost:3000:

成功打印了日志。但是和 nest 内置的日志格式不一样。我们可以模仿下。

添加更多

安装 dayjs 格式化日期:

bash 复制代码
npm install dayjs

安装 chalk 来打印颜色:

bash 复制代码
npm install chalk@4

注意:这里用的是 chalk 4.x 的版本。

然后来实现下 nest 日志的格式:

typescript 复制代码
import { LoggerService } from '@nestjs/common';
import * as chalk from 'chalk';
import * as dayjs from 'dayjs';
import { createLogger, format, Logger, transports } from 'winston';

export class WinstonLoggerService implements LoggerService {
  private logger: Logger;

  constructor() {
    this.logger = createLogger({
      level: 'debug',
      transports: [
        new transports.Console({
          format: format.combine(
            format.colorize(),
            format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
            format.printf(({ context, level, message, time }) => {
              const appStr = chalk.green(`[NEST]`);
              const contextStr = chalk.yellow(`[${context}]`);

              return `${appStr} ${time} ${level} ${contextStr} ${message} `;
            }),
          ),
        }),
      ],
    });
  }

  getTime() {
    return dayjs(Date.now()).format('YYYY-MM-DD HH:mm:ss');
  }

  log(message: string, context: string) {
    this.logger.info(message, { context, time: this.getTime() });
  }

  error(message: string, context: string) {
    this.logger.error(message, { context, time: this.getTime() });
  }

  warn(message: string, context: string) {
    this.logger.warn(message, { context, time: this.getTime() });
  }
}

main.ts 替换 Nest.js 内置的 logger:

加下第二个上下文参数:

访问下页面:打印:

然后加一个 File 的 transport。

会生成日志文件:

封装成动态模块

我们可以将 winston 集成到 nest 中,社区也有对应的包:nest-winston,我们来自己封装下叭:

logger.service.ts:

然后在 AppModule 引入下:

改一下 main.ts 里用的 logger:

正常打印:

使用:

相关推荐
耶啵奶膘1 小时前
uniapp+firstUI——上传视频组件fui-upload-video
前端·javascript·uni-app
视频砖家2 小时前
移动端Html5播放器按钮变小的问题解决方法
前端·javascript·viewport功能
lyj1689972 小时前
vue-i18n+vscode+vue 多语言使用
前端·vue.js·vscode
程序员岳焱3 小时前
Java 与 MySQL 性能优化:Java 实现百万数据分批次插入的最佳实践
后端·mysql·性能优化
麦兜*3 小时前
Spring Boot启动优化7板斧(延迟初始化、组件扫描精准打击、JVM参数调优):砍掉70%启动时间的魔鬼实践
java·jvm·spring boot·后端·spring·spring cloud·系统架构
大只鹅4 小时前
解决 Spring Boot 对 Elasticsearch 字段没有小驼峰映射的问题
spring boot·后端·elasticsearch
小白变怪兽4 小时前
一、react18+项目初始化(vite)
前端·react.js
ai小鬼头4 小时前
AIStarter如何快速部署Stable Diffusion?**新手也能轻松上手的AI绘图
前端·后端·github
IT_10244 小时前
Spring Boot项目开发实战销售管理系统——数据库设计!
java·开发语言·数据库·spring boot·后端·oracle
bobz9654 小时前
动态规划
后端