Skip to content

Instantly share code, notes, and snippets.

@itse4elhaam
Created February 1, 2024 07:09
Show Gist options
  • Save itse4elhaam/6d6d510f27112fa0f12e1d39b3aafcce to your computer and use it in GitHub Desktop.
Save itse4elhaam/6d6d510f27112fa0f12e1d39b3aafcce to your computer and use it in GitHub Desktop.
A standard morgan and chalk configuration for express logs
const morgan = require('morgan');
const chalk = require('chalk');
const { REQ_COLORS } = require('../lib/constants');
morgan.token('params', (req, res) => {
return JSON.stringify(req.params);
});
morgan.token('query', (req, res) => {
return JSON.stringify(req.query);
});
morgan.token('body', (req, res) => {
return JSON.stringify(req.body);
});
morgan.token('colored-status', (req, res) => {
const status = res.statusCode;
const color = status >= 500 ? 'red' : status >= 400 ? 'yellow' : status >= 300 ? 'cyan' : 'green';
return chalk[color](status);
});
morgan.token('colored-method', (req, res) => {
const method = req.method;
const color = REQ_COLORS[method];
return chalk[color](method);
});
const morganMiddleware = morgan(
(tokens, req, res) => {
const method = tokens['colored-method'](req, res);
const url = tokens.url(req, res);
const status = tokens['colored-status'](req, res);
const contentLength = tokens.res(req, res, 'content-length');
const responseTime = tokens['response-time'](req, res);
const params = tokens.params(req, res);
const query = tokens.query(req, res);
const body = tokens.body(req, res);
return `\n${method} ${url} ${status} ${contentLength} - ${responseTime} ms Params: ${params} Query: ${query} Body: ${body}\n`;
},
{
// Stream for morgan logs (you can customize this as needed)
stream: process.stdout,
}
);
module.exports = morganMiddleware;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment