Last active
June 7, 2020 08:25
-
-
Save evindunn/77811f013db1501256aa3b7fb7179461 to your computer and use it in GitHub Desktop.
NodeJS Winston Logger
This file contains hidden or 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
const winston = require("winston"); | |
const winstonFmt = winston.format; | |
const TIMESTAMP_FMT = "YYYY-MM-DD HH:mm:ss"; | |
const NANOS_IN_MILLI = BigInt(1e6); | |
const LOG_LEVEL = process.env.LOG_LEVEL || "warn"; | |
const LOG_LEVELS = { | |
levels: { | |
error: 0, | |
warn: 1, | |
info: 2, | |
debug: 3 | |
}, | |
colors: { | |
error: "red", | |
warn: "yellow", | |
info: "reset", | |
debug: "reset" | |
} | |
}; | |
function formatter(info) { | |
return `[${info.timestamp}][${info.level.toUpperCase()}][${info.label.toUpperCase()}] ${info.message}`; | |
} | |
class Logger { | |
constructor() { | |
throw new Error("Don't instantiate directly, call getLogger()"); | |
} | |
static getLogger(label) { | |
return winston.createLogger({ | |
level: LOG_LEVEL, | |
levels: LOG_LEVELS.levels, | |
transports: new winston.transports.Console(), | |
format: winston.format.combine( | |
winstonFmt.label({ label: label.toString() }), | |
winstonFmt.timestamp({ format: TIMESTAMP_FMT }), | |
winstonFmt.splat(), | |
winstonFmt.printf(formatter), | |
winstonFmt.colorize({ all: true, colors: LOG_LEVELS.colors }) | |
) | |
}); | |
} | |
static middleware(logger) { | |
return (req, res, next) => { | |
const responseStartTime = process.hrtime.bigint(); | |
res.on("finish", () => { | |
const responseFinishTime = (process.hrtime.bigint() - responseStartTime) / NANOS_IN_MILLI; | |
logger.info( | |
"%s %s %s %d %s - %d ms", | |
req.headers["forwarded"] || req.headers["x-forwarded-for"] || req.connection.remoteAddress, | |
req.method, | |
req.originalUrl, | |
res.statusCode, | |
res.get("Content-Length") ? res.get("Content-Length") : "-", | |
`${responseFinishTime}`.slice(-1) | |
); | |
}); | |
next(); | |
}; | |
} | |
} | |
module.exports = Logger; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment