Skip to content

Instantly share code, notes, and snippets.

@shinaisan
Created September 1, 2018 12:02
Show Gist options
  • Save shinaisan/2d7ccb2cc9166be07a27036be567cb92 to your computer and use it in GitHub Desktop.
Save shinaisan/2d7ccb2cc9166be07a27036be567cb92 to your computer and use it in GitHub Desktop.
morgan custom format example
const express = require('express');
const fs = require('fs');
const path = require('path');
const morgan = require('morgan');
const morganFormat = (tokens, req, res) => (
JSON.stringify({
'remote-addr': tokens['remote-addr'](req),
'remote-user': tokens['remote-user'](req),
'date': tokens.date(req, res, 'iso'),
method: tokens.method(req, res),
url: tokens.url(req, res),
status: tokens.status(req, res),
'content-length': tokens.res(req, res, 'content-length'),
'response-time-ms': tokens['response-time'](req, res),
referrer: tokens.referrer(req)
})
);
const accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'});
const app = express();
app.use(morgan(morganFormat, { stream: accessLogStream }));
let dict = {
hello: 'greeting',
greeting: 'acknowledgement',
cat: 'feline',
feline: 'carnivore',
placental: 'mammal'
};
app.get('/', (req, res) => res.send('Hello World!'));
app.get('/get/:key', (req, res) => {
const key = req.params.key;
const value = dict[key];
if (!value) {
res.status(404).send(key + ' not found.');
return;
}
res.send(value);
});
app.post('/post/:key/:value', (req, res) => {
const key = req.params.key;
const value = req.params.value;
if ((!key) || (!value)) {
res.status(500).send('Bad request.');
return;
}
dict[key] = value;
res.status(200).send('OK');
});
app.use(express.static('public'));
app.listen(3000, () => console.log('Example app listening on port 3000!'));
{
"name": "morgan-custom-format-example",
"version": "1.0.0",
"description": "morgan custom format example",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "[email protected]",
"license": "ISC",
"dependencies": {
"express": "^4.16.3",
"morgan": "^1.9.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment