Skip to content

Commit

Permalink
Fix logger so that error stacks are also logged on console
Browse files Browse the repository at this point in the history
  • Loading branch information
hagopj13 committed Oct 27, 2019
1 parent 5a967bf commit 3a12d87
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 13 deletions.
19 changes: 13 additions & 6 deletions src/config/logger.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,24 @@
const winston = require('winston');
const config = require('./config');

const enumerateErrorFormat = winston.format(info => {
if (info instanceof Error) {
Object.assign(info, { message: info.stack });
}
return info;
});

const logger = winston.createLogger({
level: config.env === 'development' ? 'debug' : 'info',
format: winston.format.combine(
enumerateErrorFormat(),
config.env === 'development' ? winston.format.colorize() : winston.format.uncolorize(),
winston.format.splat(),
winston.format.printf(({ level, message }) => `${level}: ${message}`)
),
transports: [
new winston.transports.Console({
stderrLevels: ['error'],
format: winston.format.combine(
config.env === 'development' ? winston.format.colorize() : winston.format.uncolorize(),
winston.format.splat(),
winston.format.printf(({ level, message }) => `${level}: ${message}`)
),
handleExceptions: true,
}),
],
});
Expand Down
6 changes: 0 additions & 6 deletions src/config/mongoose.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
const mongoose = require('mongoose');
const config = require('./config');
const logger = require('./logger');

mongoose.connection.on('error', error => {
logger.error(`MongoDB connection error ${error}`);
process.exit(1);
});

const connect = async () => {
return mongoose.connect(config.mongodbUrl, {
Expand Down
2 changes: 1 addition & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const exitHandler = () => {
};

const unexpectedErrorHandler = error => {
logger.error(`Unexpected error ${error}`);
logger.error(error);
exitHandler();
};

Expand Down
5 changes: 5 additions & 0 deletions src/middlewares/error.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const httpStatus = require('http-status');
const config = require('../config/config');
const logger = require('../config/logger');
const AppError = require('../utils/AppError');

const errorConverter = (err, req, res, next) => {
Expand Down Expand Up @@ -28,6 +29,10 @@ const errorHandler = (err, req, res, next) => {
...(config.env === 'development' && { stack: err.stack }),
};

if (config.env === 'development') {
logger.error(err);
}

res.status(statusCode).send(response);
};

Expand Down

0 comments on commit 3a12d87

Please sign in to comment.