nest.js使用nest-winston日志一

nest-winston文档

nest-winston - npm

参考:nestjs中winston日志模块使用 - 浮的blog - SegmentFault 思否

安装

cnpm install --save nest-winston winston

cnpm 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文件夹,要自定路径。

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Nest.js中,你可以使用crypto-js库进行加密和解密操作。crypto-js是一个JavaScript加密库,它提供了各种常见的加密算法,如AES、DES、SHA等。要在Nest.js使用crypto-js,你需要先安装它。 首先,在你的Nest.js项目中打开终端,并运行以下命令来安装crypto-js库: ```bash npm install crypto-js ``` 安装完成后,你可以在你的代码中引入crypto-js使用它的加密和解密功能。以下是一个简单的示例: ```typescript import { Injectable } from "@nestjs/common"; import * as CryptoJS from 'crypto-js'; @Injectable() export class CryptoUtil { encrypt(text: string, secretKey: string): string { return CryptoJS.AES.encrypt(text, secretKey).toString(); } decrypt(ciphertext: string, secretKey: string): string { const bytes = CryptoJS.AES.decrypt(ciphertext, secretKey); return bytes.toString(CryptoJS.enc.Utf8); } } ``` 上面的代码示例展示了如何在Nest.js的CryptoUtil类中使用crypto-js库进行加密和解密操作。在encrypt方法中,我们使用AES算法和给定的密钥对文本进行加密。在decrypt方法中,我们使用相同的密钥对密文进行解密。 你可以根据自己的需求调整和扩展这个示例。请注意,为了使用crypto-js库,你需要在文件头部引入CryptoJS,并使用`import * as CryptoJS from 'crypto-js';`语句。 希望这个示例对你理解在Nest.js使用crypto-js进行加解密有所帮助。如果你还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值