我正在使用摩根登录node.js。
我喜欢在预定义格式模式'dev‘中提供的状态码着色,但我使用的是自定义格式。
如何才能获得与'dev‘模式相同的颜色?
根据morgan文档,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'));发布于 2018-05-30 22:27:09
您可以很容易地使用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);发布于 2016-10-28 15:02:00
是的,默认情况下,它不能将你的输出着色到控制台。
你可以参考这篇文章,它需要“粉笔”模块的帮助,以便将输出着色到控制台。
或者我所做的是,我使用了默认的' dev‘配置,并为我的自定义令牌添加了额外的配置,这使得默认的dev输出保持不变。如下所示:
app.use(morgan('dev'));
app.use(morgan('auth_id - :userid user_email - :email'));这将完成您正在尝试做的事情,但是,morgan的第二个输出将出现在换行符中。
发布于 2018-09-22 06:58:58
我在所有工作中都使用这个粉笔摩根配置,并将其作为一个中间件包含在express应用程序中。
const morgan = require ('morgan');
const chalk = require ('chalk');
const morganChalk = morgan(function (tokens, req, res) {
return [
chalk.green.bold(tokens.method(req, res)),
chalk.red.bold(tokens.status(req, res)),
chalk.white(tokens.url(req, res)),
chalk.yellow(tokens['response-time'](req, res) + ' ms'),
].join(' ');
});
module.exports = {
morganChalk
}https://stackoverflow.com/questions/36284015
复制相似问题