Express Morgan not writing logs to file or STDOUT

Viewed 5702

I have an Express application that I would like to add logging to. I installed Morgan and set up the middleware in the file which manages my API calls:

/src/api/calls.js

the morgan middleware is set up to send the logging results to a file: 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

the api routes are required into the app.js file and the apiRoutes function is called:

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);

the problem is - I'm not getting any logging data written into my errors.txt file or even in the console when I change the code to simply STDOUT. What am I missing here?

4 Answers

In case you are running/debugging your Node code from VS Code, then this problem is caused by VS Code.

Morgan writes to console via process.stdout.write, which is not supported by VS Code's Debug Console. The Debug Console will show only things written via console.log.

There are two ways to fix this. Both include adding entires to launch.json:

  • first solution - add "console": "integratedTerminal"
  • second solution - add "outputCapture": "std" (will not respect log colors)

I found this solutions here:

when using express, it works for me

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

In my case, when I moved the following code to the start of the app.js file, then it started working:

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

For some reason, when this was at the beginning of the file:

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

And this was at the end:

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

Then it didn't work. I didn't figure out why.

Related