Skip to content

Instantly share code, notes, and snippets.

@DavidTPate
Last active July 27, 2023 13:53
Show Gist options
  • Save DavidTPate/9ecd5c07f6e1c0fd90aafa8ddbbf20c3 to your computer and use it in GitHub Desktop.
Save DavidTPate/9ecd5c07f6e1c0fd90aafa8ddbbf20c3 to your computer and use it in GitHub Desktop.
A gist which shows how to run Morgan in Express with output in JSON
const express = require('express');
const app = express();
const morgan = require('morgan');
const port = 3000;
// Define your morgan logger to log JSON to your client
// The object here takes your keys and strings that use
// the morgan token format
app.use(morgan(format({
response_time: ':response-time',
remote_addr: ':remote-addr',
remote_user: ':remote-user',
status: ':status',
url: ':url', // etc.; any non-standard tokens you would have to implement
})));
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
function format(obj) {
var keys = Object.keys(obj);
var token = /^:([-\w]{2,})(?:\[([^\]]+)\])?$/;
return function (tokens, req, res) {
var data = {};
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var val = token.exec(obj[key]);
data[key] = val !== null ? tokens[val[1]](req, res, val[2]) : obj[key];
}
console.log(JSON.stringify(data, null, 4));
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment