首页 > 解决方案 > 使用 pino api 将来自不同模块的日志添加到文件中

问题描述

我正在研究nodejs项目。如何在不同的模块上添加 Pino 记录器并将日志添加到 aa 文件中。我可以在控制台上添加日志。您能否建议使用 pino 在一个日志文件中添加所有日志。

记录器.ts

const childProcess = require('child_process');
const stream = require('stream');
 
// Environment variables
const cwd = process.cwd();
const {env} = process;
const logPath = `${cwd}/log`;
console.log(`-------${logPath}`)
export function getLogger( verbosity: string) {
    // Create a stream where the logs will be written
    const logThrough = new stream.PassThrough();
    //const log = pino({name: 'project'}, logThrough);
    
    // Log to file
    const child = childProcess.spawn(process.execPath, [
        require.resolve('pino-tee'),`${logPath}/warn.log`
    ], {cwd, env});
    
    logThrough.pipe(child.stdin);
    return pino({ level: verbosity || process.env.LOG_LEVEL || 'info' }).child({logThrough})
}

abcts

const obj = require('../logger')
const logger = obj.getLogger()
const expressLogger = expressPino({ logger });
const app = express()
    .use(expressLogger)
    .use('/',.........

bcd.ts

const obj = require('../logger')
const logger = obj.getLogger()
logger.warn("You are running with local configuration.");

标签: node.jsexpresspinojs

解决方案


推荐阅读