Skip to content

Instantly share code, notes, and snippets.

@jeonghwan-kim
Last active December 23, 2015 00:24
Show Gist options
  • Save jeonghwan-kim/065dabf47987e729735a to your computer and use it in GitHub Desktop.
Save jeonghwan-kim/065dabf47987e729735a to your computer and use it in GitHub Desktop.
var morgan = require('morgan');
/**
* morgan wrapper
* @returns {morgan}
*/
module.exports = function setLogger() {
// http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html
var red = '\x1B[31m',
green = '\x1B[32m',
yellow = '\x1B[33m',
cyan = '\x1B[36m',
white = '\x1B[37m',
endColor = '\033[0m';
// Redefind method token
morgan.token('method', function (req, res) {
var color;
if (req.method === 'GET') color = green;
else if (req.method === 'POST') color = cyan;
else if (req.method === 'PUT') color = yellow;
else if (req.method === 'DELETE') color = red;
else color = white;
return color + req.method + endColor;
});
// Redefine status token
morgan.token('status', function (req, res) {
var color;
if (res.statusCode < 300) color = green;
else if (res.statusCode < 400) color = cyan;
else if (res.statusCode < 500) color = yellow;
else if (res.statusCode < 600) color = red;
else color = white;
return color + res.statusCode + endColor;
});
// Create a token for request body
morgan.token('body', function (req, res) {
return white + 'body: ' + JSON.stringify(req.body) + endColor;
});
return morgan(':method :url :status :response-time ms :body');
};
@jeonghwan-kim
Copy link
Author

Usage:

var express = require('express'),
    http = require('http'),
    bodyParser = require('body-parser'),
    morganHelper = require('./morgan-helper'),
    app,
    server;

app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(morganHelper());

server = http.createServer(app);
server.listen(9000, function () {
  console.log('server listening on 9000. check the log messages.');
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment