Nodejs - How to use morgan with debug

岁酱吖の 提交于 2019-12-04 13:09:36

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!