将morgan与logger一起使用时,stream.write不是函数 [英] stream.write is not a function when using morgan with logger

查看:150
本文介绍了将morgan与logger一起使用时,stream.write不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我正在尝试使用morgan和winston为nodejs实现记录器.

Basically i am trying to implement logger for the nodejs , using morgan and winston.

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

When i am trying to use morgan , throwing an error of stream.write is not a function.

因为我要获取文件名,所以我正在传递模块,因此从模块对象开始有一个名为filename的属性.

Since i want get the file name , i am passing the module, from module object there is a property called filename.

下面是我的代码.

//Winston.js

// Winston.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;

推荐答案

在App.js上,尝试更改

On App.js, try changing

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

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

即使我不知道为什么,这似乎仍然有效.

This seems to work even though I don't know why.

这篇关于将morgan与logger一起使用时,stream.write不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆