How to log every message in new line using winston

2019-09-19 13:34发布

we are using winston logger to log events to nodejs fs , i want to write every event into new line using winston, is it possible with to achieve that task using winston library or any other approach that works with nodejs.

ctrl.js

var winston = require('winston');
var consumer = new ConsumerGroup(options, topics);
        console.log("Consumer topics:", getConsumerTopics(consumer).toString());
        logger = new (winston.Logger)({
            level: null,
            transports: [
//                new (winston.transports.Console)(),
                new (winston.transports.File)({
                    filename: './logs/st/server.log',
                    maxsize: 1024 * 1024 * 20,//15728640 is 15 MB
                    timestamp: false,
                    json: false,
                    formatter: function (options) {
                        return options.message;
                    }
                })
            ]
        });
        function startConsumer(consumer) {
            consumer.on('message', function (message) {
                logger.log('info', message.value);
                //callback(message.value);
                io.io().emit('StConsumer', message.value);
            });
            consumer.on('error', function (err) {
                console.log('error', err);
            });
        };
        startConsumer(consumer);

1条回答
在下西门庆
2楼-- · 2019-09-19 14:10

I use something like this, using the split module:

const split = require('split');
const winston = require('winston');

winston.emitErrs = false;

const logger = new winston.Logger({
  transports: [
    new winston.transports.File({
      level: 'debug',
      filename: 'server.log',
      handleExceptions: true,
      json: false,
      maxsize: 5242880,
      maxFiles: 5,
      colorize: false,
      timestamp: true,
    }),
    new winston.transports.Console({
      level: 'debug',
      handleExceptions: true,
      json: false,
      colorize: true,
      timestamp: true,
    }),
  ],
  exitOnError: false,
});

logger.stream = split().on('data', message => logger.info(message));

module.exports = logger;

It works pretty well for my needs by your mileage may vary.

The split module:

查看更多
登录 后发表回答