Last active
December 23, 2015 10:49
-
-
Save sthawali/6624232 to your computer and use it in GitHub Desktop.
Log everything with winston + express-winston
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var http = require('http'); | |
var app = express(); | |
var expressWinston = require('express-winston'); | |
var winston = require('winston'); | |
var fs = require('fs'); | |
var app = express(); | |
var server = http.createServer(app); | |
// Setup | |
function Setup(app) { | |
this._app = app; | |
this._logPath = 'FILE_PATH'; // Change to your logpath | |
// varify that log file is present | |
fs.openSync(this._logPath, 'a'); | |
// Capture log | |
this.activityLog(); | |
// Build basic response | |
this.inRoutes(); | |
// Log Error | |
this.errorLog(); | |
} | |
// setup winston logger | |
Setup.prototype.activityLog = function() { | |
var that = this; | |
this._app.use(expressWinston.logger({ | |
transports: [ | |
new (winston.transports.Console)({ | |
json: true, | |
colorize: true | |
}), | |
new (winston.transports.File)({ | |
filename: that._logPath | |
}) | |
] | |
})); | |
}; | |
Setup.prototype.inRoutes = function() { | |
var that = this; | |
this._app.all('*', function(req, res, next) { | |
// Setup response object in log | |
req._routeWhitelists.res = ['response']; | |
req.store = req.store || {}; | |
res.response = res.response || { | |
status: true, | |
error: {code: 0, message: ''}, | |
data: {} | |
}; | |
next(); | |
}); | |
}; | |
Setup.prototype.errorLog = function() { | |
var that = this; | |
this._app.use(expressWinston.errorLogger({ | |
transports: [ | |
new (winston.transports.Console)({ | |
json: true, | |
colorize: true | |
}), | |
new (winston.transports.File)({ | |
filename: that._logPath | |
}) | |
] | |
})); | |
}; | |
// call setup | |
new Setup(app); | |
app.get('/', function(req, res) { | |
res.writeHeader(200, {'Content-Type' : "text/html"}); | |
res.write("<h1>Success</h1>"); | |
res.end("<p style='border:1px dotted red'>Check your log file!</p>"); | |
}); | |
app.get('/error', function(req, res, next) { | |
return next(new Error("This is an error and it should be logged to the console")); | |
}); | |
server.listen(5678, function(){ | |
console.log("Server is running.."); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment