Juned Ansari
Juned Ansari

Reputation: 5283

How do I log every request and errors in logfile

I have created one middleware to Log every request and errors of API, can any one tell me the best practice to do that?

logging.js

const winston = require('winston');
module.exports = function(req, res, next) {
  const logger = winston.createLogger({
    levels: winston.config.syslog.levels,
    transports: [
      new winston.transports.File({
        filename: 'Logs/combined.log',
        level: 'info'
      })
    ],
    exitOnError: false
  });

  var logmsg = {
    'Request IP':req.ip,
    'Method':req.method,
    'URL':req.originalUrl,
    'statusCode':res.statusCode,
    'headers':req.headers,
    'Time':new Date()
  };

  process.on('unhandledRejection', (reason, p) => {
    logger.error('exception:'+reason);
    res.status(200).json({
        'statuscode': 200,
        'message': 'Validation Error',
        'responsedata': 'Unhandled Exception Occured'
    });  
  });
  logger.log('info', logmsg);
  next();
}

Upvotes: 0

Views: 390

Answers (2)

Biplab Malakar
Biplab Malakar

Reputation: 788

You can use a middleware, which will log your all request. This middleware should be place at the top of all routes.

app.use((req,res,next)=> {
   console.log(`${req.method}- ${req.protocol}:// ${req.get('host')}{req.originalUr}`)
   next();
})

You can use try-catch to get the error and transfer all errors to a common function.

try{
 // all code
}catch(err){
  return sendError(res, err);
}

sendError(res, err){
  return res.status(200).json({
        'statuscode': 200,
        'message': err.message,
        'responsedata': 'Unhandled Exception Occured'
    });
}

Upvotes: 1

mtkopone
mtkopone

Reputation: 6443

Assuming you are using express or similar, add the following to where you configure your express:

const logging = require('$path/to/logging')
const app = express.createServer(options)

app.all('*', logging)

This will make the middleware get called for all requests.

You should also initialize winston outside of the middleware call, since it is a one-time operation. So move the winston.createLogger call outside of the function scope.

As another note, process.on('unhandledRejection', handler) is a global hook, so you should also not use it inside the middleware function scope. You will end up with 1 listener per request, which are never cleaned up, and which will all fire when an unhandled rejection occurs. (They will fail, since the responses are already sent.)

Upvotes: 2

Related Questions