Node.js / Pino.js:如何在单独的线程中轮换日志

问题描述 投票:0回答:1

我正在尝试使用 pino 登录到我的节点应用程序服务器,并且我确实有一些大型日志即将到来,因此每天轮换文件会更实用。

所以我用了

pino.multistream()
require('file-stream-rotator')

我的代码可以工作,但出于性能原因,我不想在主线程中使用流。

根据文档,我应该使用

pino.transport()

[

pino.multistream()
] 与
pino.transport()
不同,因为所有流都将在主线程(即创建 pino 实例的线程)内执行。 https://github.com/pinojs/pino/releases?page=2

但是,我无法将

pino.transport()
file-stream-rotator
结合起来。

我的代码不能完全工作 -> 记录第一个条目,但不可导出,因为它会阻止脚本并出现错误

抛出新的错误('工人已退出')

主要文件

const pino = require('pino')

const transport = pino.transport({
  target: './custom-transport.js'
})

const logger = pino(transport)
logger.level = 'info'

logger.info('Pino: Start Service Logging...')

module.exports = {
  logger
}

自定义-transport.js 文件

const { once } = require('events')
const fileStreamRotator = require('file-stream-rotator')

const customTransport = async () => {
  const stream = fileStreamRotator.getStream({ filename: 'myfolder/custom-logger.log', frequency: 'daily' })
  await once(stream, 'open')
  return stream
}

module.exports = customTransport
javascript node.js logging pinojs
1个回答
0
投票

file-stream-rotator
导出
EventEmitter
的实例,而不是
Stream
。尽管
EventEmitter
实例的行为类似于流,但我怀疑它是否正确实现了
Stream

您是否尝试过使用中间

PassThrough
流?

const { once } = require("events");
const { getStream: getRotatingFileStream } = require("file-stream-rotator");
const path = require("path");
const { PassThrough } = require("stream");

module.exports = async function Transport({ destinationDir, auditFilePath }) {
if (!destinationDir || !auditFilePath)
  throw new Error("destinationDir and auditFilePath are required to initialize this transport");

const streamLikeEmitter = getRotatingFileStream({
  filename: path.join(destinationDir, "%DATE%"),
  date_format: "YYYY-MM-DD",
  extension: ".log",
  size: "10M",
  max_logs: 20,
  create_symlink: true,
  audit_file: auditFilePath,
});

const passThroughStream = new PassThrough();

passThroughStream.on("data", (chunk) => {
  streamLikeEmitter.write(chunk);
});

await once(streamLikeEmitter, "open");

return passThroughStream;
};
© www.soinside.com 2019 - 2024. All rights reserved.