Winston: Attempt to write logs with no transports

后端 未结 3 1820
不思量自难忘°
不思量自难忘° 2021-02-20 10:24

I\'m trying to set up an access log and an error log for my express server using Winston, but I seem to be doing something wrong.

Here is my attempt at a config file:

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-20 10:25

    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 version 3.x.x, new (winston.Logger) has been replaced by winston.createLogger (https://github.com/bithavoc/express-winston/issues/175)

提交回复
热议问题