Logging in express js to a output file?

What is best way to log my express js webserver? The inbuilt express.logger() just displays logs on screen. Can I also log them into a file in /log folder? Also the current logger automatically logs the request and responses. I need to log some application data into the log files. Can this be done using express.logger?

Regards, Lalith


Solution 1:

To send the express or connect logs to a file use Node's writeStream. For example to send the express logs to ./myLogFile.log :

open the stream to your file in append mode with :

var logFile = fs.createWriteStream('./myLogFile.log', {flags: 'a'}); //use {flags: 'w'} to open in write mode

then, in your express config use :

app.use(express.logger({stream: logFile}));

should also work for connect.logger.

Solution 2:

Look at the connect middleware that express extends. The express.logger() is the same as the connect.logger():

http://expressjs.com/api.html#middleware

http://www.senchalabs.org/connect/logger.html

The logger has a stream option that can be set where you want the output to go. By default it sends it to stdout. Also you can specify the log format you want to use.

Solution 3:

You should try winston

var logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)(),
    new (winston.transports.File)({ filename: 'somefile.log' })
  ]
});