Skip to content

Instantly share code, notes, and snippets.

@kailashyogeshwar85
Created November 16, 2019 11:30
Show Gist options
  • Save kailashyogeshwar85/24d77f6c6d1070f3c6219e6808775299 to your computer and use it in GitHub Desktop.
Save kailashyogeshwar85/24d77f6c6d1070f3c6219e6808775299 to your computer and use it in GitHub Desktop.
NodeJS server with Bunyan
const bunyan = require('bunyan');
const format = require('bunyan-format');
const express = require('express');
const bodyParser = require('body-parser')
const FS = require('fs');
const _ = require('lodash');
global.logger = configureLogger();
const app = express();
// for logging request
const logRequest = function (req, res, next) {
const start = new Date();
const end = res.end;
res.end = function(payload, encoding){
let responseTime = Date.now() - start.getTime();
end.call(res, payload, encoding);
const contentLength = Number(res.getHeader('Content-Length'));
const _data = {
req: _.pick(req, ['method', 'url']),
res: _.pick(res, ['statusCode']),
responseTime: responseTime,
contentLength: isNaN(contentLength) ? 0 : contentLength
}
logger.info('%s %s %s %d %dms - %d bytes', (req.hostname || ''), _data.req.method, _data.req.url, _data.res.statusCode, _data.responseTime, _data.contentLength);
}
next();
}
app.use(logRequest());
app.use(bodyParser.json());
function configureLogger(){
const logFile = './api.LOG';
const ws = FS.createWriteStream(logFile, { flags: 'a' });
// formatting options for stdout
const formatOut = format({ outputMode: 'short', levelInString: true, colorFromLevel: {
20: 'blue',
30: 'green',
40: 'yellow',
50: 'red',
60: 'brightRed'
}});
const fileFormatter = format({outputMode: 'bunyan', level: true }, ws);
const logger = bunyan.createLogger({
name: 'API Logger',
level: 'debug',
streams: [
{
level: 'debug',
stream: fileFormatter
},
{
level: 'info',
stream: fileFormatter
},
{
level: 'debug',
stream: process.stdout
}
]
});
logger.log = function (message) {
logger.debug(message);
}
return logger;
}
app.listen(4044, () => {
logger.log("API Server Listening on PORT 4044");
});
@liu-xiao-guo
Copy link

Hi, when I run your server.js, I get an error:

// for logging request
const logRequest = function (req, res, next) {
const start = new Date();
console.log("nice");
console.log(req);
console.log(res);
const end = res.end;

In the above, it prints out req and res are both undefined. Can you help? thanks

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