使用内置Logger
import { Controller, Get, Logger, Post } from '@nestjs/common'; import { UserService } from './user.service'; import { ApiOperation, ApiTags } from '@nestjs/swagger'; import { ConfigService } from '@nestjs/config'; @ApiTags('用户') @Controller('user') export class UserController { private logger = new Logger(UserController.name); constructor( private userService: UserService, private configService: ConfigService, ) { this.logger.log('UserController init'); } @ApiOperation({ summary: '获取用户' }) @Get() getUserLists(): any { this.logger.log('获取用户列表'); return this.userService.getUsers(); } @ApiOperation({ summary: '添加用户' }) @Post() addUser() { return this.userService.addUser(); } }
Pino
pnpm i nestjs-pino
使用
import { NestFactory } from '@nestjs/core' import { Controller, Get, Module } from '@nestjs/common' import { LoggerModule, Logger } from 'nestjs-pino' @Controller() export class AppController { constructor(private readonly logger: Logger) {} @Get() getHello() { this.logger.log('something') return `Hello world` } } @Module({ controllers: [AppController], imports: [LoggerModule.forRoot()] }) class MyModule {} async function bootstrap() { const app = await NestFactory.create(MyModule) await app.listen(3000) } bootstrap()
格式化日志数据
LoggerModule.forRoot({ pinoHttp: { transport: { target: 'pino-pretty', options: { colorize: true, }, }, }, })
pino-roll
保存日志到文件
npm i pino-roll
使用
如果是开发环境那么就console打印,生产环境就是保存到txt文件
LoggerModule.forRoot({ pinoHttp: { transport: { targets: [ { level: 'info', target: 'pino-pretty', options: { colorize: true, }, }, { level: 'info', target: 'pino-roll', options: { file: join('log', 'log.txt'), frequency: 'daily', // hourly size: '10m', mkdir: true, }, }, ], }, }, })
winston
pnpm install --save nest-winston winston
main.ts写入
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { generateDocument } from '@/swagger'; import { createLogger } from 'winston'; import * as winston from 'winston'; import { utilities as nestWinstonModuleUtilities, WinstonModule, } from 'nest-winston'; async function bootstrap() { const instance = createLogger({ transports: [ new winston.transports.Console({ format: winston.format.combine( winston.format.timestamp({ format: 'YYYY-MM-DD HH:MM:ss' }), winston.format.ms(), nestWinstonModuleUtilities.format.nestLike('MyApp', { colors: true, prettyPrint: true, }), ), }), ], }); const app = await NestFactory.create(AppModule, { logger: WinstonModule.createLogger({ instance }), }); app.setGlobalPrefix('api'); generateDocument(app); await app.listen(3000); } bootstrap();
nestjs支持重写Logger对象,以上代码,创建了一个Logger实例,替换nestjs的Logger实例
app.module.ts代码
import { Global, Logger, Module } from '@nestjs/common'; import { UserModule } from './user/user.module'; import { ConfigModule, ConfigService } from '@nestjs/config'; import * as config from 'config'; import { TypeOrmModule } from '@nestjs/typeorm'; const database = config.get('database'); const { type, host, port, username, password, db, synchronize } = database; const env = process.env.NODE_ENV === 'development'; //global设置全局模块,其他模块可以不如导入就能使用 @Global() @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, // 是否是全局模块 }), TypeOrmModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: (configService: ConfigService) => { return { type, host, port, username, password, database: db, entities: ['dist/src/entitys/*.{.ts,.js}'], //扫描本项目中.entity目录文件 synchronize, //定义数据库表结构与实体类字段同步(这里一旦数据库少了字段就会自动加入,根据需要来使用) logging: ['error'], }; }, }), UserModule, ], controllers: [], providers: [Logger], exports: [Logger],//这里要导出Logger对象 }) export class AppModule {}
使用
import { Controller, Get, Logger, Post } from '@nestjs/common'; import { UserService } from './user.service'; import { ApiOperation, ApiTags } from '@nestjs/swagger'; import { ConfigService } from '@nestjs/config'; @ApiTags('用户') @Controller('user') export class UserController { constructor( private userService: UserService, private configService: ConfigService, private readonly logger: Logger, ) { this.logger.log('UserController init'); } @ApiOperation({ summary: '获取用户' }) @Get() getUserLists(): any { this.logger.log('获取用户'); return this.userService.getUsers(); } @ApiOperation({ summary: '添加用户' }) @Post() addUser() { return this.userService.addUser(); } }
Logger对象已经被替换为自己定义的Logger对象了。
winston滚动日志
pnpm install winston-daily-rotate-file
main.ts代码
import 'winston-daily-rotate-file'; const transport = new winston.transports.DailyRotateFile({ dirname: 'logs', filename: 'application-%DATE%.log', datePattern: 'YYYY-MM-DD-HH', zippedArchive: true, maxSize: '20m', maxFiles: '14d', }); async function bootstrap() { const instance = createLogger({ transports: [ new winston.transports.Console({ format: winston.format.combine( winston.format.timestamp({ format: 'YYYY-MM-DD HH:MM:ss' }), winston.format.ms(), nestWinstonModuleUtilities.format.nestLike('MyApp', { colors: true, prettyPrint: true, }), ), }), transport, ], }); const app = await NestFactory.create(AppModule, { logger: WinstonModule.createLogger({ instance }), }); app.setGlobalPrefix('api'); generateDocument(app); await app.listen(3000); } bootstrap();
发表评论
侧栏公告
寄语
譬如朝露博客是一个分享前端知识的网站,联系方式11523518。
热评文章
标签列表
热门文章
友情链接