Search code examples
node.jswinston

Log every request and error messages using winston


I am able to log every request and error message into separate logfiles(request.log and uncaughtExceptions.log) but want to merge this two files into one file only called logs.log like

var logmsg = {
        'Request IP',
        'Method':req.method,
        'URL':req.originalUrl,
        'statusCode':res.statusCode,
        'headers':req.headers,
        'Time':new Date(),
        'ErrorMessage':'Error Message if any with file name with line number and proper error message' 
    };

Working Code:

const express = require('express');
const winston = require('winston');
require('express-async-errors');

module.exports = function() {
  winston.handleExceptions(
    new winston.transports.File({ filename: 'uncaughtExceptions.log' }));

  process.on('unhandledRejection', (ex) => {
    throw ex;
  });

  winston.add(winston.transports.File, { filename: 'request.log' });

}

What I have Tried:

logging.js

const express = require('express');
const { createLogger, format, transports } = require('winston');
const { combine, timestamp, label, printf } = format;

const myFormat = printf(info => {
  return (info.timestamp + " | " +
          info.trace[0].file + ":" + info.trace[0].line + " | " +
          info.message.split("\n")[0]);
});

module.exports = function() {
  const logger = createLogger({
    format: combine(timestamp(), myFormat)
  });

  logger.exceptions.handle(new transports.File({ filename: 'logs.log' }));

  process.on('unhandledRejection', (reason, p) => {
    throw p;
  });

}

it displays strange error message, i have no idea how to resolve it.

Error message:

enter image description here

server.js

const express = require('express');
const winston = require("winston");
const app = express();

//to Log errors
require('./startup/logging')();
//routes will contains all the routes list
require('./startup/routes')(app);

//PORT
const port = process.env.PORT || 3000;
app.listen(port,() => winston.info(`Listening on port ${port}....`));

routes.js

const express = require('express');
const reqres = require('../middlewares/reqreslog');
module.exports = function(app){
   //Every Request Response Logging Middleware
   app.use(reqres);
   app.get('/', async (req, res) => {
        res.json("testing"+a);
    });
});

reqreslog.js

var winston = require('winston');
module.exports = function(req, res, next) {
    var logmsg = {
        'Request IP':req.ip,
        'Method':req.method,
        'URL':req.originalUrl,
        'statusCode':res.statusCode,
        'headers':req.headers,
        'Time':new Date(),
        'ErrorMessage':'Display Error If Any for this request' 
    };
    winston.log('info', logmsg);
    next();
}

Solution

  • Winston logging works on the basis of log level info,debug,error etc.. If you want to log everything into the same log file you have to give level info.

    const logger = winston.createLogger({
      levels: winston.config.syslog.levels,
      transports: [
        new winston.transports.File({
          filename: 'combined.log',
          level: 'info'
        })
      ]
    });
    
    
    process.on('unhandledRejection', (reason, p) => {
        logger.error('exception occur');
        throw reason;
      });
    

    Read more about log level in winstonjs - https://github.com/winstonjs/winston#using-logging-levels