有没有办法在 pino 日志输出到控制台之前检索它?例如,如果我有以下内容
import pino from 'pino';
// Create a logger instance
const logger = pino({
level: 'info', // Set the log level
prettyPrint: true, // Optional: Pretty print the logs
});
// Export the logger instance if you want to use it in other files
export default logger;
然后
logger.info("in function x");
我在控制台中看到以下内容 {“级别”:20“,时间戳”:“2024-08-16T16:53:55.368Z”,“pid”:26068,“主机名”:“xxx”,“traceId”:“ebacaa63-5cb6-47b5-8cb9 -8f3600a8c35f","消息":"在函数 x 中"}
有什么方法可以让我检索此日志而不将其写入文件(只需将 logger.info 的输出存储到本地变量中?
您可以使用自定义流将 Pino 记录器的输出捕获到变量中,并在代码中访问该变量的内容。
参见示例:
import pino from "pino";
import { Writable } from "node:stream";
// This is the variable where the log message will be captured
const logs = [];
const customStream = new Writable({
write(chunk, _encoding, callback) {
logs.push(chunk.toString());
callback();
},
});
const logger = pino({ level: "info" }, customStream);
logger.info("This is a test log");
logger.error("This is an error");
console.log("Captured logs:", logs);