3

Morgan outputs requests directly to the console.

How can I redirect them to npm debug so that it follows the same format as the other stuff which is being logged?

My debug.js config looks like the following:

import debug from 'debug';

const LOG_PREFIX = 'api';

const info = debug(`${LOG_PREFIX}:info`);
const dev = debug(`${LOG_PREFIX}:dev`);
const error = debug(`${LOG_PREFIX}:error`);

export {
  info,
  dev,
  error,
};

And I currently log other stuff like:

import { info } from './debug';

info('App is up and running!');

My current morgan call is:

app.use(morgan('combined'));
zurfyx
  • 31,043
  • 20
  • 111
  • 145
  • Better to use express-winston. It can log a lot of things to different transports like file, console, newtork, db. Lot of things that morgan cannot do. Highly configurable. I replaced morgon because I couldn't make it log into MongoDB easily – Nidhin David Feb 02 '17 at 18:49

2 Answers2

6

Morgan accepts an optional parameter which is the stream.

By default it points to process.stdout, the console.

Since what it does it to call stream.write, you can easily build a quick stream which redirects to your debug.

app.use(morgan('combined', { stream: { write: msg => info(msg) } }));

Generically (but still ES6), that would be:

import debug from 'debug';
const info = debug('info');
app.use(morgan('combined', { stream: { write: msg => info(msg) } }));

ES5:

var info = require('debug')('info');
app.use(morgan('combined', { stream: { write: function(msg) { info(msg); } }}));
zurfyx
  • 31,043
  • 20
  • 111
  • 145
4

when using morgan ˋstreamˋ combined with ˋdebugˋ, it´s best to do:

app.use(morgan('combined', { stream: { write: msg => info(msg.trimEnd()) } }));

The reason: morgan add a new line at the end of the msg when calling the stream.write(...) function.

Timisorean
  • 1,388
  • 7
  • 20
  • 30
DevelDevil
  • 41
  • 1