Morgan (node.js):使用自定义格式时着色状态代码(如“dev”中)

2024-03-01

我正在使用 Morgan 登录 Node.js。

我喜欢预定义格式模式“dev”中提供的状态代码着色, 但我使用的是自定义格式。

如何获得与“开发”模式相同的颜色?

根据摩根文档,开发格式如下:

 :method :url :status :response-time ms - :res[content-length]

当我使用它时,它不会变色:

// does not color
app.use(morgan(':method :url :status :response-time ms - :res[content-length]')); 

但是当我使用预定义的“dev”时,它会变色!

app.use(morgan('dev'));

您可以非常轻松地使用 chalkJS 进行着色。

import morgan from 'morgan';
import chalk from 'chalk'; // or you can use the require('chalk') syntax too

export const morganMiddleware = morgan(function (tokens, req, res) {
    return [
        '\n\n\n',
        chalk.hex('#ff4757').bold('????  Morgan --> '),
        chalk.hex('#34ace0').bold(tokens.method(req, res)),
        chalk.hex('#ffb142').bold(tokens.status(req, res)),
        chalk.hex('#ff5252').bold(tokens.url(req, res)),
        chalk.hex('#2ed573').bold(tokens['response-time'](req, res) + ' ms'),
        chalk.hex('#f78fb3').bold('@ ' + tokens.date(req, res)),
        chalk.yellow(tokens['remote-addr'](req, res)),
        chalk.hex('#fffa65').bold('from ' + tokens.referrer(req, res)),
        chalk.hex('#1e90ff')(tokens['user-agent'](req, res)),
        '\n\n\n',
    ].join(' ');
});

app.use(morganMiddleware);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Morgan (node.js):使用自定义格式时着色状态代码(如“dev”中) 的相关文章

随机推荐