Skip to content

Instantly share code, notes, and snippets.

@markusand
Created January 15, 2022 18:33
Show Gist options
  • Save markusand/91ed6ad99ef246d2e32ed7fe73d44e11 to your computer and use it in GitHub Desktop.
Save markusand/91ed6ad99ef246d2e32ed7fe73d44e11 to your computer and use it in GitHub Desktop.
Express logger module with Winston + Morgan
import winston from 'winston';
import morgan from 'morgan';
import json from 'morgan-json';
/* WINSTON */
const filterLevel = level => winston.format(info => info.level === level ? info : undefined)();
const logger = winston.createLogger({
levels: { error: 0, warn: 1, info: 2, debug: 3, http: 4 },
transports: [
new winston.transports.Console({
level: 'debug',
format: winston.format.printf(info => `[${info.level.toUpperCase()}] ${info.message}`),
}),
new winston.transports.File({
filename: "logs/errors.log",
level: "error",
format: winston.format.combine(
winston.format.timestamp(), // Add a timestamp
winston.format.json() // Save in JSON format
)
}),
new winston.transports.File({
filename: "logs/http.log",
level: 'http',
format: filterLevel('http'),
}),
],
});
export default logger;
/* MORGAN */
morgan.token('user-id', req => req.user || '-');
const format = json(':date[iso] :remote-addr :user-id :method :url :status :res[content-length] :response-time');
const stream = { write: message => logger.http(JSON.parse(message)) };
export const httpLogger = morgan(format, { stream });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment