node.jsexpressloggingmorgan

Morgan logger in an express app doesn't create new lines with each entry


I'm having a problem getting the morgan logger module to write each log entry on a new line in my log file.

I've written an express app to authenticate users into a resource we subscribe to, and I need to add logging to the app. I have morgan set up to write to a file, however, each entry in the log file is written on the same line, instead of writing to a new line.

Here's what I have in my code

//requiring express and morgan
var express = require('express');
var morgan = require('morgan');

//defining the file to write log entries to
var accessLogStream = fs.createWriteStream(path.join('logs', 'access.log'), {flags: 'a'});

//defining what to log with morgan
app.use(morgan(':date[iso], :remote-addr, :status, :response-time ms', {stream: accessLogStream}));

What am I missing? I tried adding /n to the end of the morgan format like:

app.use(morgan(':date[iso], :remote-addr, :status, :response-time ms /n', {stream: accessLogStream}));

but that resulted in an error. The error says:

undefined:8
(tokens["response-time](req, res) || "-") + " ms

SyntaxError: Invalid or unexpeceted token

Solution

  • Morgan actually writes with a new line: https://github.com/expressjs/morgan/blob/master/index.js#L130

    Note that this is a unix newline. If you are on Windows you should read the file with an application that does render non-Windows newlines (i.e. not Notepad).