Nodejs Nestjs日志管理插件nestjs-winston-logger的使用

Nodejs Nestjs日志管理插件nestjs-winston-logger的使用
nestjs-winston-logger 是一个用于 NestJS 的日志管理插件,它基于 Winston 库来提供强大的日志功能。以下是如何在你的 NestJS 项目中使用 nestjs-winston-logger 的步骤:

安装依赖

首先,你需要安装 winstonnestjs-winston(因为 nestjs-winston-logger 已经被弃用,所以现在推荐使用 nestjs-winston)。

npm install winston @nestjs/winston

配置日志模块

接下来,在你的 NestJS 项目中配置日志模块。你可以在 app.module.ts 或者专门的日志模块中进行配置。

import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { WinstonModule } from '@nestjs/winston';
import { format, transports } from 'winston';

@Module({
  imports: [
    WinstonModule.forRoot({
      transports: [
        new transports.Console({
          format: format.combine(
            format.timestamp(),
            format.simple(), // 或者使用其他格式化方式,如:format.json()
          ),
        }),
      ],
    }),
  ],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: WinstonModule.WinstonInterceptor,
    },
  ],
})
export class AppModule {}

使用日志服务

你可以在任何 NestJS 服务或控制器中注入 Logger 来使用日志功能。

import { Injectable, Logger } from '@nestjs/common';

@Injectable()
export class AppService {
  private readonly logger = new Logger(AppService.name);

  getHello(): string {
    this.logger.log('Logging a message');
    this.logger.warn('Logging a warning');
    this.logger.error('Logging an error');
    return 'Hello World!';
  }
}

自定义日志级别

如果你需要自定义日志级别,可以通过传递额外的选项来自定义日志行为。

import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { WinstonModule } from '@nestjs/winston';
import { format, transports } from 'winston';

@Module({
  imports: [
    WinstonModule.forRoot({
      transports: [
        new transports.Console({
          format: format.combine(
            format.timestamp(),
            format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`),
          ),
        }),
      ],
      levels: {
        silly: 0,
        verbose: 1,
        info: 2,
        http: 3,
        warn: 4,
        debug: 5,
        error: 6,
      },
    }),
  ],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: WinstonModule.WinstonInterceptor,
    },
  ],
})
export class AppModule {}

通过以上步骤,你可以为你的 NestJS 应用程序设置一个强大且灵活的日志系统。


3 回复

当然,了解nestjs-winston-logger可以让您的Node.js应用日志记录变得既强大又灵活!首先,确保您已经安装了@nestjs/winstonwinston。接着,在您的NestJS项目中配置它,就像给应用程序穿上了一件超级英雄的斗篷。

npm install @nestjs/winston winston

然后,在您的app.module.ts中,添加WinstonModule到imports数组,并配置您的日志级别和格式:

import { LoggerModule } from '@nestjs/winston';
import * as winston from 'winston';

@Module({
  imports: [
    LoggerModule.forRoot({
      transports: [
        new winston.transports.Console(),
        new winston.transports.File({ filename: 'combined.log' }),
      ],
    }),
  ],
})
export class AppModule {}

现在,您可以在服务或控制器中注入Logger,开始记录信息、警告、错误等:

import { Logger } from '@nestjs/common';

@Injectable()
export class CatsService {
  constructor(private readonly logger: Logger) {}

  findAll(): void {
    this.logger.log('Finding all cats!');
  }
}

这样,您就拥有了一个功能齐全的日志系统,可以轻松地跟踪应用的行为,就像是拥有了一双透视眼!


nestjs-winston-logger 是一个用于NestJS应用的日志管理插件。它基于 Winston 日志库,可以让你轻松地进行日志记录、配置和管理。下面我将指导你如何安装并使用这个插件。

1. 安装

首先,你需要通过npm或yarn安装 winstonnestjs-winston

npm install winston nestjs-winston

或者使用 yarn:

yarn add winston nestjs-winston

2. 配置

接下来,你需要在你的 NestJS 应用中配置 WinstonModule。你可以在主模块(通常是 AppModule)中配置它:

import { Module } from '@nestjs/common';
import { WinstonModule } from 'nest-winston';
import * as winston from 'winston';

@Module({
  imports: [
    WinstonModule.forRoot({
      transports: [
        new winston.transports.Console({
          format: winston.format.combine(
            winston.format.timestamp(),
            winston.format.simple(),
          ),
        }),
        new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
        new winston.transports.File({ filename: 'logs/combined.log' }),
      ],
    }),
  ],
  // 其他配置...
})
export class AppModule {}

这里我们配置了三个传输器:控制台、错误日志文件和组合日志文件。你可以根据需要调整这些设置。

3. 使用日志服务

一旦配置完成,你就可以在任何服务或控制器中注入 Logger 服务来记录日志:

import { Injectable, Logger } from '@nestjs/common';

@Injectable()
export class AppService {
  private readonly logger = new Logger(AppService.name);

  getHello(): string {
    this.logger.log('Handling GET /hello request');
    return 'Hello World!';
  }

  handleException() {
    try {
      throw new Error('Something went wrong!');
    } catch (err) {
      this.logger.error(err.message, err.stack);
    }
  }
}

在这个例子中,我们创建了一个名为 AppService 的服务,并使用 Logger 记录了日志。我们使用了 .log() 方法来记录常规信息,使用 .error() 方法来记录异常。

这样,你就可以在NestJS应用中方便地使用 nestjs-winston-logger 来管理日志了。

nestjs-winston-logger 是一个用于 NestJS 的日志管理插件,基于 Winston。首先安装依赖:

npm install winston @nestjs/winston

然后配置模块:

import { Module } from '@nestjs/common';
import { WinstonModule } from '@nestjs/winston';

@Module({
  imports: [
    WinstonModule.forRoot({
      transports: [
        new (require('winston-daily-rotate-file'))({
          filename: 'application-%DATE%.log',
          datePattern: 'YYYY-MM-DD',
          zippedArchive: true,
          timestamp: true,
        }),
      ],
    }),
  ],
})
export class LoggerModule {}

在服务中注入使用:

import { Injectable, Logger } from '@nestjs/common';
import { createLogger, transports } from 'winston';

@Injectable()
export class AppService {
  private readonly logger = createLogger();

  constructor() {
    this.logger.add(new transports.DailyRotateFile({
      filename: 'application-%DATE%.log',
      datePattern: 'YYYY-MM-DD',
    }));
  }

  async someMethod() {
    this.logger.info('This is an info message');
  }
}

这样可以实现日志记录的功能。

回到顶部