Express Morgan不会将日志写入文件或STDOUT

时间:2016-03-09 23:04:49

标签: node.js express logging

我有一个Express应用程序,我想添加日志记录。我安装了Morgan并在管理我的API调用的文件中设置了中间件:

/src/api/calls.js

摩根中间件设置为将日志记录结果发送到文件:errors.txt

    var express = require('express'),
        app = express(),
        dbConfig = require('../config/db.config'),
        connectToMongo = require('./db.js'),
        bodyParser = require("body-parser"),
        ObjectId = require('mongodb').ObjectID,
        morgan = require('morgan'),
        fs = require('fs'),
        Sb;

    //middleware
    var accessLogStream = fs.createWriteStream('../sample/errors.txt', {flags: 'a'})
    app.use(morgan('combined',  {stream: accessLogStream}));

    app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
    });
    app.use(bodyParser.urlencoded({ extended: true }));

module.exports = function apiRoutes(app) {
  app.get("/v1/api/sample/:call", function(req, res, next) {
     //route db calls and code here
  });
}

/app.js

api路由需要进入app.js文件并调用apiRoutes函数:

var express = require('express');
var app = express();
var config = require('./src/config/server.config');
//api and server
var http = require('http');
var server = new http.Server(app);

//load the api calls for the server
var apiRoutes = require('./src/api/calls.js');
apiRoutes(app);

问题是 - 当我将代码更改为STDOUT时,我没有将任何日志记录数据写入我的errors.txt文件或甚至在控制台中。我在这里错过了什么?

3 个答案:

答案 0 :(得分:6)

我想出来了 - 日志代码需要位于app.js文件中,而不是在包含api调用的文件中。我知道日志代码需要成为第一个中间件,但我没有意识到在实例化服务器的新实例之后需要它。

var express = require('express'),
    app = express(),
    config = require('./src/config/server.config'),
    morgan = require('morgan'),
    fs = require('fs'),
//api and server
    http = require('http'),
    server = new http.Server(app); 

//set up the logger
var accessLogStream = fs.createWriteStream(__dirname + '/access.log', {flags: 'a'})
app.use(morgan('combined',  {"stream": accessLogStream}));


//load the api calls for the server
var apiRoutes = require('./src/api/calls.js');
apiRoutes(app);

答案 1 :(得分:0)

使用快递时,它对我有用

app.use(morgan('dev'));

答案 2 :(得分:0)

就我而言,当我将以下代码移至app.js文件的开头时,它开始起作用:

app.use(logger('combined'));
app.use(logger('common', {
    stream: fs.createWriteStream(__dirname + '/access.log', {flags: 'a'})
}));

由于某种原因,当它位于文件的开头时:

app.use(logger('combined'));

这就是结尾:

app.use(logger('common', {
    stream: fs.createWriteStream(__dirname + '/access.log', {flags: 'a'})
}));

然后它不起作用。我不知道为什么。