如果我使用我的自定义记录器函数而不是使用像 winston 或 log4js 这样的库,节点服务器的性能会受到影响吗?

Will performance of a Node server be affected if I use my custom logger function instead of using libraries like winston or log4js?

我是 nodejs 的新手,我正在尝试创建一个函数,用于将自定义格式的日志记录到文件和控制台。以下是我为此目的使用的功能。

module.exports.log =function(req,res) 
{

res.on('finish', function() 
{

point = new Date(); 
clientIP = req.ip;
request = req.protocol + '://' + req.get('host') + req.originalUrl;
userAgent = req.get('User-Agent');
method = req.method;
statusCode = res.statusCode;


output =
"["
+point.toDateString()
+"] -- ["
+point.getHours()
+":"
+point.getMinutes()
+":"
+point.getSeconds()
+"] -- [client IP : "
+clientIP
+"] -- [user agent : "
+userAgent
+"] -- [method : "
+method
+"] -- [request : "
+request
+"] -- [response code : "
+statusCode
+"]"
;

console.log(output);
var fs = require('fs');
fs.appendFile('QAB.log', output, function (err) 
{
    if (err) throw err;
});

})

}

不知道这样做是否正确。我查看了 winston、log4js-node 等库。但我只是想自己创建它。我想知道如果我使用 winston、log4js 或其他东西是否会获得性能优势。

或者换一种说法..我做错了吗?这会影响我的节点服务器的性能吗?

编写自己的记录器没有任何问题,因为编写任何模拟任何 npm 模块的定制代码都没有问题。

我可能会建议不要自己编写,原因与我建议不要编写自己的身份验证或安全中间件的原因相同。这些问题都已经解决了,足够通用,大家可以使用。

在每个日志语句中写入一个文件非常昂贵,因为写入磁盘会增加请求的处理时间。

此外,如果您正在写入文件,如果您正在考虑将所有日志存储在那里,则需要在某个时候轮换文件,如果可以,最好转到系统日志。

像 winston (https://www.npmjs.com/package/winston) 这样最受欢迎的记录器可以添加一个传输,它将执行您想要的自定义日志记录,并以最快的方式写入文件。

如果您追求速度,那么 pico 非常好 (https://github.com/pinojs/pino),而且速度更快,具体取决于您将日志发送到哪里。