nest-winston文檔
nest-winston - npm
參考:nestjs中winston日志模塊使用 - 浮的blog - SegmentFault 思否
安裝
cnpm install --save nest-winston winstoncnpm install winston-daily-rotate-file
在main.ts中
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ResponseInterceptor } from './common/response.interceptor'
import { HttpExceptionFilter } from './common/http-exception.filter';
import { createLogger } from 'winston';
import * as winston from 'winston';
import { WinstonModule, utilities, } from 'nest-winston'
import 'winston-daily-rotate-file';async function bootstrap() {//日志const instance = createLogger({transports: [new winston.transports.Console({level: 'info',format: winston.format.combine(winston.format.timestamp(),utilities.format.nestLike())}),new winston.transports.DailyRotateFile({level: 'error',dirname: 'logs',filename: 'error-%DATE%.log',datePattern: 'YYYY-MM-DD',zippedArchive: true,maxSize: '10m',maxFiles: '14d',format: winston.format.combine(winston.format.timestamp(),winston.format.simple(),),}),new winston.transports.DailyRotateFile({level: 'info',dirname: 'logs',filename: 'info-%DATE%.log',datePattern: 'YYYY-MM-DD',zippedArchive: true,maxSize: '10m',maxFiles: '14d',format: winston.format.combine(winston.format.timestamp(),winston.format.simple(),),}),]})const logger = WinstonModule.createLogger({instance})const app = await NestFactory.create(AppModule, {logger});app.setGlobalPrefix('api');//路由前綴//全局響應攔截app.useGlobalInterceptors(new ResponseInterceptor());//全局異常攔截 只能有一個 寫入日志app.useGlobalFilters(new HttpExceptionFilter(logger));await app.listen(7000);
}
bootstrap();
其中自定義異常 自動寫入日志記錄
app.useGlobalFilters(new HttpExceptionFilter(logger));
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, LoggerService } from '@nestjs/common';
import { Request, Response } from 'express';
/*** 封裝 自定義 http 異常攔截*/@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {//把錯誤異常自動加到日志constructor(private logger: LoggerService ) {}catch(exception: HttpException, host: ArgumentsHost) {const ctx = host.switchToHttp();// 請求和響應對象const response = ctx.getResponse<Response>();const request = ctx.getRequest<Request>();// http狀態碼const status = exception.getStatus();this.logger.error(exception.message, exception.stack);let json = {code: status,msg: exception.message || exception.name, //exception.getResponse(),timestamp: new Date().toISOString(),path: request.url,method: request.method,}response.status(status).json(json);}
}
控制臺打印結果
自動生成的logs文件夾
如果在生產環境,logs文件夾,要自定路徑。