Winston based express logger that includes request, process, unique id and user information
npm install winston-express-request-loggerList of elements added to the log as a prefix
* Process id e.g pId: 9472
* Unique request identifier e.g uId: cidstmimz000ob43upnw7xp2b
* User identifier e.g cId: 123
* User ip address e.g cIP: 127.0.0.1
* User action e.g cAction: GET /api/user/55dc48232a8708a3078e995a
Additionally if there is an err object as part of the log arguments the error stack trace will be printed in the logs.
npm install winston-express-request-logger```
// Initialise logger
var winston = require('winston');
var winstonExRegLogger = require("winston-express-request-logger");
winstonExRegLogger.createLogger({
transports: [
new (winston.transports.File)({
filename: 'knugget-service.log',
handleExceptions: true,
timestamp:true,
level:"info"
}),
new (winston.transports.Console)({
handleExceptions: true,
timestamp: true,
level:"info"
})
],
exitOnError: false
});
The second step is to add the request interceptor to express in order to get the necessary information from the express request object. The user id in this case is retrieved by getting the cookie named id from express (req.cookies['id']).
`
// Request Interceptor setup
var winstonExRegLogger = require("winston-express-request-logger");
function configureApp(app, env) {
.....
.....
app.use(winstonExRegLogger.requestDetails);
.....
.....
}
`
An optional step if you would like to override the user id printed by the module, is to add your own interceptor that initialises the req.loggerUserId variable. This needs to go before the requestDetails one.
`
// Custom Request Interceptor setup
var winstonExRegLogger = require("winston-express-request-logger");
function configureApp(app, env) {
.....
.....
var customUserID = function customUserID(req, res, next) {
req.loggerUserId = 123;
next();
};
app.use(customUserID);
app.use(winstonExRegLogger.requestDetails);
.....
.....
}
`
`
// Logging
var logger = require("winston-express-request-logger").getLogger();
logger.info(req,"Get the user's details");
// prints 2015-08-26T13:59:16.659Z - info: pId:9677 - uId:cidsul8ry000pgt3ugwebvei5 - cId:55dc48232a8708a3078e995a - cIP: 127.0.0.1 - cAction: GET /api/user/55dc48232a8708a3078e995a Get user details
logger.info("Get the user's details");
// prints 2015-08-26T13:59:16.659Z - info: Get the user's details
``