Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 将morgan与记录器一起使用时,stream.write不是一个函数_Node.js_Logging_Winston_Morgan - Fatal编程技术网

Node.js 将morgan与记录器一起使用时,stream.write不是一个函数

Node.js 将morgan与记录器一起使用时,stream.write不是一个函数,node.js,logging,winston,morgan,Node.js,Logging,Winston,Morgan,基本上,我正在尝试使用morgan和winston为NodeJ实现logger 当我试图使用morgan时,抛出stream.write错误不是一个函数 因为我想得到文件名,所以我要传递模块,从模块对象中有一个名为filename的属性 下面是我的代码 //温斯顿js const appRoot = require('app-root-path'); const { createLogger, format, transports } = require('winston'); const {

基本上,我正在尝试使用morgan和winston为NodeJ实现logger

当我试图使用morgan时,抛出stream.write错误不是一个函数

因为我想得到文件名,所以我要传递模块,从模块对象中有一个名为filename的属性

下面是我的代码

//温斯顿js

const appRoot = require('app-root-path');
const { createLogger, format, transports } = require('winston');
const { combine, timestamp, label, printf } = format;
const path = require('path');

// Custom Format
const customFormat = printf(info => {
    return `${new Date(info.timestamp)} || [${info.label}] || ${info.level}: ${info.message} `
})

// Return the last folder name in the path and the calling
// module's filename.
const getLabel = function (moduleDetails) {
    if (Object.keys(moduleDetails).length > 0) {
        let parts = moduleDetails.filename.split(path.sep)
        return parts.pop();
    }else{
        return;
    }
}

// define the custom settings for each transport (file, console)
var options = (moduleDetails) => ({
    file: {
        level: "info",
        timestamp: new Date(),
        filename: `${appRoot}/logs/app.log`,
        handleExceptions: true,
        json: true,
        maxsize: 5242880,
        maxFiles: 5,
        colorize: false,
        label: getLabel(moduleDetails)
    },
    console: {
        level: "debug",
        handleExceptions: true,
        json: false,
        colorize: true,
    }
})

//instantiate a new Winston Logger with the settings  defined above
let logger = function (moduleDetails) {
    return createLogger({
        format: combine(
            label({label:getLabel(moduleDetails)}),
            timestamp(),
            customFormat
        ),
        transports: [
            new transports.File(options(moduleDetails).file)
        ],
        exitOnError: false // do not exit on handled exceptions
    })
}



// create  a stream object with 'write' function that will be used by 'morgan' 
// logger({})["stream"] = {
//     write: function (message, encoding) {
//         // use the 'info' log  level so the output will be picked up by both transports
//         // (file and console) 
//         logger().info(message)
//     }
// }

// If we're not in production then log to the `console` with the format:
// `${info.timestamp} || [${info.label}] || ${info.level}: ${info.message}`
//  like in the log  file

if (process.env.NODE_ENV !== 'prod') {
    logger({}).add(new transports.Console(options({}).console));
}



module.exports = logger 
module.exports.stream = {
    write: function (message, encoding) {
        // use the 'info' log  level so the output will be picked up by both transports
        // (file and console) 
        logger().info(message)
    }
}
//App.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var morgan = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var winston = require('./config/winston')(module);

var app = express();


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(morgan('combined', { "stream": winston.stream}));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // add this line to include winston logging
  winston.error(`${err.status || 500} || ${err.message} || ${req.originalUrl} || ${req.method} || ${req.ip}` )

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});



module.exports = app;

我认为您没有正确导出模块,应该是:

var winston = require('./config/winston');
winston.logger(module);
相反:

var winston = require('./config/winston')(module);

在App.js上,尝试更改

app.use(morgan('combined', { "stream": winston.stream}));


虽然我不知道为什么,但这似乎有效。

感谢您的回复,但您可以查看问题行9中的app.js文件。它已经正确导入了。问题在于stream.write。调用createLogger是对象具有“stream”键时的结果。将module.exports.stream更改为streamXXX或任何名称,您将看到第9行仍然有效。因此stream.write是错误的,因为我们使用的是相同的名称。您是这么说的吗?如果我将名称从stream更改为streamX,我不会收到错误,但当我检查日志文件时,日志文件为空。基本上不是写摩根日志。将morgan日志写入文件时,我应该做些什么更改吗?您是否按照我在回答中所说的做了?并手动调用记录器功能是否可以在流记录器中记录请求主体部分??
app.use(morgan('combined', { "stream": winston.stream.write}));