Winston: Attempt to write logs with no transports

限于喜欢 提交于 2019-12-04 02:41:40
Terry Lennox

I'd try something like this, put all the logger related stuff into a module logger.js:

logger.js

    var winston = require('winston');
    var path = require('path');

    // Set this to whatever, by default the path of the script.
    var logPath = __dirname;

    const tsFormat = () => (new Date().toISOString());

  const errorLog = winston.createLogger({
  transports: [
    new winston.transports.File({
      filename: path.join(logPath, 'errors.log'),
      timestamp: tsFormat,
      level: 'info'})
  ]
});

const accessLog = winston.createLogger({
  transports: [
    new winston.transports.File({
      filename: path.join(logPath, 'access.log'),
      timestamp: tsFormat,
      level: 'info'})
  ]
});


    module.exports = {
        errorLog: errorLog,
        accessLog: accessLog
    };

and then test in index.js:

index.js

var logger = require('./logger');

logger.errorLog.info('Test error log');
logger.accessLog.info('Test access log');

You should see log lines like:

errors.log:

{"level":"info","message":"Test access log","timestamp":"2018-03-14T07:51:11.185Z"}

access.log:

{"level":"info","message":"Test error log","timestamp":"2018-03-14T07:51:11.182Z"}

EDIT

On Winston last version, new (winston.Logger) has been replaced by winston.createLogger (https://github.com/bithavoc/express-winston/issues/175)

1 Logger + console logging for development purpose:

logger.js

var logPath = '';
var log_level = '';

const log = winston.createLogger({
  level: log_level,
  format: winston.format.json(),
  transports: [
    new winston.transports.File({
      filename: path.join(logPath, 'access.log'),
      timestamp: tsFormat,
      level: log_level
    }),
    new winston.transports.File({
      filename: path.join(logPath, 'error.log'),
      timestamp: tsFormat,
      level: 'error'
    }),
  ]
});

if (process.env.NODE_ENV !== 'production') {
  log.add(new winston.transports.Console({
    format: winston.format.simple()
  }));
}

module.exports = {
  log: log
};

app.js

const logger = require('./logger');

logger.log.info("starting application..");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!