Skip to content

Commit 0d5d78d

Browse files
committed
Add winston logging library. Log each API request and error.
1 parent ec069bb commit 0d5d78d

File tree

3 files changed

+35
-2
lines changed

3 files changed

+35
-2
lines changed

config/express.js

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import compress from 'compression';
66
import methodOverride from 'method-override';
77
import cors from 'cors';
88
import httpStatus from 'http-status';
9+
import expressWinston from 'express-winston';
10+
import winstonInstance from './winston';
911
import routes from '../server/routes';
1012
import config from './env';
1113
import * as utilityService from '../server/services/utility';
@@ -25,6 +27,18 @@ app.use(methodOverride());
2527
// enable CORS - Cross Origin Resource Sharing
2628
app.use(cors());
2729

30+
// enable detailed API logging in dev env
31+
if (config.NODE_ENV === 'development') {
32+
expressWinston.requestWhitelist.push('body');
33+
expressWinston.responseWhitelist.push('body');
34+
app.use(expressWinston.logger({
35+
winstonInstance,
36+
meta: true, // optional: log meta data about request (defaults to true)
37+
msg: 'HTTP {{req.method}} {{req.url}} {{res.statusCode}} {{res.responseTime}}ms',
38+
colorStatus: true // Color the status code (default green, 3XX cyan, 4XX yellow, 5XX red).
39+
}));
40+
}
41+
2842
// mount all routes on /api path
2943
app.use('/api', routes);
3044

@@ -40,11 +54,16 @@ app.use((req, res, next) => {
4054
return next(err);
4155
});
4256

57+
// log error in winston transports
58+
app.use(expressWinston.errorLogger({
59+
winstonInstance
60+
}));
61+
4362
// error handler, send stacktrace only during development
4463
app.use((err, req, res, next) => // eslint-disable-line no-unused-vars
4564
res.status(err.status).json({
4665
message: err.isPublic ? err.message : httpStatus[err.status],
47-
error: config.NODE_ENV === 'development' ? err : {}
66+
stack: config.NODE_ENV === 'development' ? err.stack : {}
4867
})
4968
);
5069

config/winston.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import winston from 'winston';
2+
3+
const logger = new (winston.Logger)({
4+
transports: [
5+
new (winston.transports.Console)({
6+
json: true,
7+
colorize: true
8+
})
9+
]
10+
});
11+
12+
export default logger;

package.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,11 @@
2525
"debug": "^2.2.0",
2626
"dotenv": "^2.0.0",
2727
"express": "~4.13.1",
28+
"express-winston": "^1.2.0",
2829
"http-status": "^0.2.0",
2930
"method-override": "^2.3.5",
30-
"morgan": "~1.6.1"
31+
"morgan": "~1.6.1",
32+
"winston": "^2.1.1"
3133
},
3234
"devDependencies": {
3335
"babel": "^5.8.23",

0 commit comments

Comments
 (0)