0

I'm new to nodejs and I'm trying to create a function for custom formatted logging to file and console. Below is the function which I am using for this purpose.

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;
});

})

}

Don't know if this is the right way to do it. I checked out libraries like winston, log4js-node etc. But I just thought I would create it myself.. I wanted to know if I would get a performance advantage if i use winston, log4js or something else.

Or to put it in a different way.. Am I doing this wrong? Will this affect the performance of my node server?

JPK
  • 95
  • 1
  • 8

1 Answers1

1

There is nothing wrong with writing your own logger as there is no issue with writing any bespoke code that emulates any of the npm modules.

I would probably advise against writing your own for the same reason as I would advise against writing your own authentication or security middleware. These problems have already been solved and are generic enough for everyone to use.

Writing a file in each log statement is very expensive as writing to disk will add lots of time to the processing time of your request.

Also, if you are writing to file you will need to rotate the file at some point if you are thinking of storing all your logs there, best to go to syslog if you can.

Loggers like winston (https://www.npmjs.com/package/winston) which is the most popular can have a transport added that will do the custom logging you are after and will write to file in the quickest way possible.

If you are after speed then pico is really good (https://github.com/pinojs/pino) and much faster depending on where you are shipping your logs to.

Peter Grainger
  • 4,539
  • 1
  • 18
  • 22