gpt4 book ai didi

node.js - morgan 在控制台打印输出中不使用颜色

转载 作者:太空宇宙 更新时间:2023-11-03 23:59:39 25 4
gpt4 key购买 nike

是否有限制或规则来设置/定义 morgan ,以便它仍然遵循设置的颜色模式?我目前有以下 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))
}))

它使用我设置的颜色,但当我使用自定义格式时则不使用

最佳答案

我相信您错误地调用了 morgan 函数。

根据docs :

morgan(format, options)

Create a new morgan logger middleware function using the given format and options. The format argument may be a string of a predefined name (see below for the names), a string of a format string, or a function that will produce a log entry.

The format function will be called with three arguments tokens, req, and 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 的函数中声明标记顺序及其颜色,就像 example 中所示。 :

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

关于node.js - morgan 在控制台打印输出中不使用颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55369187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com