27 lines
1.2 KiB
TypeScript
27 lines
1.2 KiB
TypeScript
import { DynamicModule } from '@nestjs/common';
|
||
import { LoggerModule } from 'nestjs-pino';
|
||
|
||
/**
|
||
* 日志配置:pino 结构化日志。
|
||
* - stdout 默认开启:开发环境用 pino-pretty 可读格式(LOG_PRETTY 默认 true),生产设 false 输出 JSON
|
||
* - 文件输出默认关闭,LOG_FILE_ENABLED=true 开启(文件始终为 JSON,便于采集)
|
||
* - 级别 LOG_LEVEL(默认 info)、路径 LOG_FILE_PATH(默认 logs/app.log)
|
||
*/
|
||
export function createLoggerModule(): DynamicModule {
|
||
const level = process.env.LOG_LEVEL ?? 'info';
|
||
const pretty = process.env.LOG_PRETTY !== 'false';
|
||
const fileEnabled = process.env.LOG_FILE_ENABLED === 'true';
|
||
const filePath = process.env.LOG_FILE_PATH ?? 'logs/app.log';
|
||
|
||
const stdoutTarget = pretty
|
||
? { target: 'pino-pretty', options: { colorize: true, translateTime: 'SYS:yyyy-mm-dd HH:MM:ss.l' } }
|
||
: { target: 'pino/file', options: { destination: 1 } };
|
||
|
||
const targets: any[] = [stdoutTarget];
|
||
if (fileEnabled) {
|
||
targets.push({ target: 'pino-roll', options: { file: filePath, size: '10m', limit: { count: 10 } } });
|
||
}
|
||
|
||
return LoggerModule.forRoot({ pinoHttp: { level, transport: { targets } } });
|
||
}
|