Binu
Binu

Reputation: 201

Morgan (node.js): Coloring status code (as in 'dev') while using custom format

I am using morgan for logging in node.js.

I like the status code coloring provided in the predefined format mode 'dev', but I am using a custom format.

How can I get the same coloring as in 'dev' mode?

Per morgan documentation, dev format is the following :

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

When I use that it does not color :

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

But when I use predefined 'dev' it does color!

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

Upvotes: 20

Views: 12000

Answers (7)

Marco Disco
Marco Disco

Reputation: 565

simply put "dev" into it:

morgan("dev")

or before your configuration, like this:

app.use(
  morgan(
    "dev",
    ":method :url :status :res[content-length] - :response-time ms - [:date[clf]]"
  )
);

Upvotes: 1

Beglex
Beglex

Reputation: 68

Also now chalk supports template string function, so you can create colored dev morgan string like this:

app.use(morgan(chalk`:method :url {green :status} :response-time ms - :res[content-length]`));

Upvotes: 1

mkb
mkb

Reputation: 1155

@Adam Reis pointed in the really nice direction. I came up with this solution:

morgan.token('splitter', (req) => {
    return "\x1b[36m--------------------------------------------\x1b[0m\n";
});
morgan.token('statusColor', (req, res, args) => {
    // get the status code if response written
    var status = (typeof res.headersSent !== 'boolean' ? Boolean(res.header) : res.headersSent)
        ? res.statusCode
        : undefined

    // get status color
    var color = status >= 500 ? 31 // red
        : status >= 400 ? 33 // yellow
            : status >= 300 ? 36 // cyan
                : status >= 200 ? 32 // green
                    : 0; // no color

    return '\x1b[' + color + 'm' + status + '\x1b[0m';
});
server.use(morgan(`:splitter\x1b[33m:method\x1b[0m \x1b[36m:url\x1b[0m :statusColor :response-time ms - length|:res[content-length]`));

Here is the result:

enter image description here

Upvotes: 10

Adam Reis
Adam Reis

Reputation: 4483

Just use the same formatting function as defined in morgan's source code for the dev format: https://github.com/expressjs/morgan/blob/master/index.js#L183-L206

Upvotes: 3

ahmedaabouzied
ahmedaabouzied

Reputation: 88

I use this chalk morgan configuration for all my work , and include it as a middleware in the express app.

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
}

Upvotes: 5

Param Singh
Param Singh

Reputation: 1366

You can use chalkJS for coloring very easily.

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

Upvotes: 20

techpool
techpool

Reputation: 61

Yes it cannot colourise your output to console by default.

You can either refer to this article which takes help of the 'chalk' module in order to colourise the output to console.

Or else what I did was I used the default 'dev' configuration and I added an extra config for my custom tokens which left the default dev output as it is. Something like this:

app.use(morgan('dev'));
app.use(morgan('auth_id - :userid user_email - :email'));

This will do what you are trying to do but, the second output of morgan will be in a newline.

Upvotes: 4

Related Questions