0

I tried to store information messages and error messages in winston logger file its sucessfully working.but I want store customizable error in winston logger file. how to fix it

winston.js

var myFormat = winston.format.combine(winston.format.timestamp({format:'YYYY-MM-DD HH:mm:ss.SSS'}),
winston.format.json())
const logger = winston.createLogger({
    level: 'info',
    format: myFormat,
    defaultMeta: { service: 'user-service' },
    transports: [
      //
      // - Write to all logs with level `info` and below to `combined.log` 
      // - Write all logs error (and below) to `error.log`.
      //
      new winston.transports.Console(),
      new winston.transports.File({ filename: 'error.log', level: 'error' }),
      new winston.transports.File({ filename: 'combined.log' })
    ],
    exceptionHandlers: [
        new winston.transports.Console(),
        new winston.transports.File({ filename: './exceptions.log', timestamp: true, maxsize: 1000000 })
      ],  
  });

  //
  // If we're not in production then log to the `console` with the format:
  // `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
  // 
  if (process.env.NODE_ENV !== 'production') {
    logger.add(new winston.transports.Console({
      format: winston.format.simple()
    }));
  }

module.exports = logger;

authentication.js

const authMiddleware = function (userPermissionLevels) {
    return (request, response, next) => {
        const token = request.header('x-auth-token');
        if (!token) return response.status(401).send("no token provided");
        const decoded = jwt.verify(token, config.get('jwtPrivateKey'));

        // Check for permissions
        if (!userPermissionLevels.includes(decoded.userPermissionLevels)) return response.status(403).send("Access denied.");

        request.user = decoded;
        next();
    }
}
I want to store "no token provided" and access deined error in winston logger file.How to acheive it.
hari prasanth
  • 716
  • 1
  • 15
  • 35

1 Answers1

1

You just need to use the created winston logger object and log the message before returning from the function.

const logger = require('./winston'); //assuming winston.js in the same level as authentication.js

const authMiddleware = function (userPermissionLevels) {
    return (request, response, next) => {
        const token = request.header('x-auth-token');
        if (!token){ 
            logger.info('no token provided');
            return response.status(401).send("no token provided");
        }
        const decoded = jwt.verify(token, config.get('jwtPrivateKey'));

        // Check for permissions
        if (!userPermissionLevels.includes(decoded.userPermissionLevels)){ 
            logger.info('Access denied.');
            return response.status(403).send("Access denied.");
        }

        request.user = decoded;
        next();
    }
}
Boney
  • 2,072
  • 3
  • 18
  • 23
  • I have another doubt info message only stored info file only and error message only stored error file .how to split the code @Boney – hari prasanth Jul 02 '19 at 07:07
  • sorry didn't get you. I don't see an info.log file in the configuration. Do you want the logs (error and info) to be stored into separate files error.log and info.log ? – Boney Jul 02 '19 at 07:47
  • Winston is allowing only 1 file transport per logger, which means only 1 file can be mentioned. You would need to try out the workarounds mentioned here: https://stackoverflow.com/questions/10045891/multiple-log-files-with-winston – Boney Jul 02 '19 at 08:22
  • @Boney I have doubt I created winston log file its successfully created but error message stored in both(info.log,error.log) file.how to separate error message stored to error file not info file. – Sudharsan Venkatraj Jul 16 '19 at 06:32