Created
March 18, 2021 01:23
-
-
Save prettyirrelevant/746fedef062ae4141ab5b1cf689ce70d to your computer and use it in GitHub Desktop.
Express JS Logging Boilerplate
This file contains 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
import morgan, { StreamOptions } from "morgan"; | |
import winston from "winston"; | |
const levels = { | |
error: 0, | |
warn: 1, | |
info: 2, | |
debug: 3, | |
}; | |
const level = () => { | |
const env = process.env.NODE_ENV || "development"; | |
const isDevelopment = env === "development"; | |
return isDevelopment ? "debug" : "info"; | |
}; | |
const colors = { | |
error: "red", | |
warn: "yellow", | |
info: "green", | |
debug: "white", | |
}; | |
winston.addColors(colors); | |
const format = winston.format.combine( | |
winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss:ms" }), | |
winston.format.colorize({ all: true }), | |
winston.format.printf( | |
(info) => `${info.timestamp} ${info.level}: ${info.message}` | |
) | |
); | |
const transports = [ | |
new winston.transports.Console(), | |
new winston.transports.File({ | |
filename: "logs/error.log", | |
level: "error", | |
}), | |
new winston.transports.File({ filename: "logs/debug.log", level: "info" }), | |
]; | |
const Logger = winston.createLogger({ | |
level: level(), | |
levels, | |
format, | |
transports, | |
}); | |
const stream: StreamOptions = { | |
write: (message) => Logger.debug(message), | |
}; | |
const skip = () => { | |
const env = process.env.NODE_ENV || "development"; | |
return env !== "development"; | |
}; | |
const morganMiddleware = morgan( | |
":method :url :status :res[content-length] - :response-time ms", | |
{ stream, skip } | |
); | |
export { Logger }; | |
export default morganMiddleware; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment