Skip to content

Instantly share code, notes, and snippets.

@shinaisan
Last active August 25, 2018 07:31
Show Gist options
  • Save shinaisan/f1cdee8f6c5d836625718a1d4a3453dd to your computer and use it in GitHub Desktop.
Save shinaisan/f1cdee8f6c5d836625718a1d4a3453dd to your computer and use it in GitHub Desktop.
Example of morgan log file rotation
const express = require('express');
const fs = require('fs');
const path = require('path');
const morgan = require('morgan');
const rfs = require('rotating-file-stream')
const logDirectory = path.join(__dirname, 'log');
// ensure log directory exists
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
// create a rotating write stream
var accessLogStream = rfs('access.log', {
interval: '1d', // rotate daily
path: logDirectory
});
const loggerType = 'combined';
const app = express();
app.use(morgan(loggerType, { 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-log-file-rotation",
"version": "1.0.0",
"description": "Example of morgan log file rotation",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"morgan",
"logger",
"Express"
],
"author": "[email protected]",
"license": "ISC",
"dependencies": {
"express": "^4.16.3",
"morgan": "^1.9.0",
"rotating-file-stream": "^1.3.7"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment