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

Rac*_*man 2 logging node.js express

我有一个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
  });
}
Run Code Online (Sandbox Code Playgroud)

/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);
Run Code Online (Sandbox Code Playgroud)

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

kne*_*ola 9

如果您从VS Code运行/调试 Node 代码,则此问题是由VS Code引起的。

Morgan通过 写入控制台,VS Code 的调试控制台process.stdout.write不支持该操作。调试控制台将仅显示通过.console.log

有两种方法可以解决这个问题。两者都包括将整体添加到launch.json

  • 第一个解决方案 - 添加"console": "integratedTerminal"
  • 第二个解决方案 - 添加"outputCapture": "std"(不尊重日志颜色)

我在这里找到了这个解决方案:


Rac*_*man 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);
Run Code Online (Sandbox Code Playgroud)

  • 这是绝对正确的。我遇到了同样的问题,你的解决方案拯救了我的日子。谢谢! (2认同)