无法在 Node.js 中使用 winston 记录错误

Unable to log errors using winston in Node.js

在 运行 以下代码中,控制台显示 logger.log 不是一个函数,即使我正在从 index.js 导出函数。

index.js

const winston = require('winston');
const error = require('./middleware/error');

const logger=winston.createLogger({transports:[new winston.transports.Console(),
                                               new winston.transports.File({filename:'logfile.log'})
                                              ]});

app.use(error);
module.exports = logger;

error.js

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

module.exports = function(err,req,res,next){
    //Log the exception 
    logger.log('error',err.message);

    res.status(500).send('Something failed.');
}

终端是这样说的:

TypeError: logger.log is not a function
    at module.exports (C:\Users\hp\Desktop\YouStart\nodejs-mosh\vidly.13- Project- Restructure the App\vidly\middleware\error.js:8:12)
    at C:\Users\hp\Desktop\YouStart\nodejs-mosh\vidly.13- Project- Restructure the App\vidly\node_modules\express-async-errors\index.js:5:20
    at Layer.handle_error (C:\Users\hp\Desktop\YouStart\nodejs-mosh\vidly.13- Project- Restructure the App\vidly\node_modules\express\lib\router\layer.js:71

循环依赖从来都不是一个好的模式。您强制 error.js 解析其导出 index.js 可以解析其导出之前 - 这可能会导致您的问题。

基本上在任何情况下都应该避免循环依赖。很简单:您永远不需要 error.js 要求 index.js,因为您可以只导出一个函数,让您将 index.js 中需要的任何内容作为参数传递。它看起来像这样:

index.js

const winston = require('winston');

const logger = winston.createLogger({transports:[new winston.transports.Console(),
                                                 new winston.transports.File({filename:'logfile.log'})
                                              ]});

const error = require('./middleware/error')(logger); //pass logger to error middleware  
app.use(error);

error.js

module.exports = function(logger) {
    //return function configured with logger to use as middleware
    return function(err,req,res,next) {
        //Log the exception 
        logger.log('error',err.message);

        res.status(500).send('Something failed.');
    }
};