是否有限制或规则必须设置/定义morgan,使其仍然符合设置的颜色模式?我现在有以下的摩根设置。
morgan.token('date', (req, res, tz) => {
return moment().tz(tz).format();
})
morgan.format('myformat', '[:date[America/Los_Angeles]][:remote-addr] ":method :url" :status :res[content-length] - :response-time ms')
app.use(morgan('myformat', function (tokens, req, res) {
return chalk.blue(tokens.method(req, res))
+ ' ' + chalk.green(tokens.url(req, res))
+ ' ' + chalk.red(tokens['response-time'](req, res))
}))当我用
app.use(morgan( function (tokens, req, res) {
return chalk.blue(tokens.method(req, res))
+ ' ' + chalk.green(tokens.url(req, res))
+ ' ' + chalk.red(tokens['response-time'](req, res))
}))它使用我的设置颜色,但当我使用自定义格式时则不使用。
发布于 2019-04-10 05:50:26
由于有了OzW指针,我能够让它使用下面的代码,并通过传递我以前使用过的格式定义。用所有想要的颜色就像一种魅力。
app.use(morgan( function (tokens, req, res) {
return chalk.yellow(moment().tz("America/Los_Angeles").format('ddd, DD MMM YYYY HH:mm:ss.SSS Z z'))
+ ' ' + chalk.blue(tokens['remote-addr'](req, res))
+ ' ' + chalk.cyanBright(tokens.method(req, res))
+ ' ' + chalk.green(tokens.url(req, res))
+ ' ' + chalk.magentaBright(tokens.status(req, res))
+ ' ' + chalk.red(tokens['response-time'](req, res))
}))发布于 2019-03-28 15:32:46
我相信您调用morgan函数是错误的。
根据文档
morgan(format, options)使用给定的格式和选项创建一个新的morgan日志记录中间件功能。format参数可以是预定义名称的字符串(请参阅下面的名称)、格式字符串的字符串或生成日志条目的函数。 格式函数将使用三个参数令牌、req和res调用.
所以当你打电话:
app.use(morgan('myformat', function (tokens, req, res) {
return chalk.blue(tokens.method(req, res))
+ ' ' + chalk.green(tokens.url(req, res))
+ ' ' + chalk.red(tokens['response-time'](req, res))
}))第二个参数(函数)不是您想要的,因为morgan认为它是options参数。我看到实现目标的唯一方法是在传递给morgan的函数中声明令牌的顺序和颜色,就像在示例中显示的那样。
const loggerMiddleware = morgan(function (tokens, req, res) {
return [
'[' + tokens['date'](req, res) + ']',
'[' + tokens["remote-addr"](req, res) + ']',
'"' + chalk.blue(tokens["method"](req, res)) + chalk.green(tokens["url"](req, res)) + '"',
// add more tokens here...
].join(' ')
});
app.use(loggerMiddleware);https://stackoverflow.com/questions/55369187
复制相似问题