node.jsdateexpressmorganmoment-timezone

Morgan logger not recording date or time correctly


The logger in my node.js app isn't recording the date or time correctly. I'm using morgan as the logging module, and moment-timezone to correctly record the date and time in my timezone (pacific stadard time). Yesterday, it was recording the date and time according to the format I set up, but today it isn't.

Here's the code for the morgan date token using moment-timezone:

morgan.token('date', (req, res, tz) => {
    return moment().tz("America/Los_Angeles").format('YYYY-MM-DD, HH:mm a');
});

And here's the code where I use the date token in morgan.format():

morgan.format('logFormat', '[:date[America/Los_Angeles]], :resource, :remote-addr, :status, :response-time ms');

Yesterday, my requests were logging with this format:

[2018-07-31, 14:57 pm], hoopla, ::1, 401, 104.144 ms

Today everything is being logged like this:

[YYYY-MM-DD, HH:mm a], hoopla, ::1, 401, 45.995 ms

The only change I made was adding new routes to the app, but each logging middleware is logging to a separate file, based on the route being used. Does anyone know why my date token isn't displaying the date anymore?


Solution

  • The morgan.token('date'... part with MomentJS logging the timezone looks all right to me!

    I bet this is a syntactic error in the custom token format. If you don't need to pass a param, according to the morgan docs, you can use custom token formats simply with semicolumn, like so :date. Therefore, try simply with:

    morgan.format('logFormat', ':date, :resource, :remote-addr, :status, :response-time ms');