Last active
August 9, 2024 16:32
-
-
Save calebhailey/ef15c0248ba826615038ed755f43a394 to your computer and use it in GitHub Desktop.
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
// VanillaJS Logger | |
// | |
// NOTE: You probably shouldn't use this in production... you've been warned. | |
let logger = {}; | |
// Log levels | |
// debug=0, info=1, log=2, warn=3, error=4 | |
const LOG_LEVELS = [ | |
"debug", | |
"info", | |
"log", | |
"warn", | |
"error", | |
]; | |
const logComponent = "api.logger"; | |
// Set log level | |
logger.setLogLevel = function(logLevel="warn") { | |
console[logLevel]("[%s] log level: %s", logComponent, logLevel); | |
let limit = LOG_LEVELS.indexOf(logLevel); | |
LOG_LEVELS.filter( function(level, index) { if (index < limit) { | |
console[logLevel]("[%s] disabling console.%s()", logComponent, level); | |
console[level] = function() {}; | |
}}); | |
}; | |
// Timestamp generator | |
logger.timestampISO = function() { | |
let now = new Date(); | |
return now.toISOString(); | |
}; | |
// Custom JSON Logger | |
logger.log = function(msg, level="log") { | |
console[level](JSON.stringify({ | |
ts: logger.timestampISO(), | |
msg: msg, | |
},null,0)) | |
}; | |
export default logger; |
Nope I agree with you. It feels easier to use this as opposed to installing another module.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is this completely insane in the-year-of-our-lord 2023?!
I've used this in two serverless projects now. Simply doing a
import logger from ./logger.js
and runninglogger.setLogLevel("warn")
gives me a one-liner for "muting" any rogueconsole.log()
debug code. I usually also set log level from an environment variable (e.g.logger.setLogLevel(env.LOG_LEVEL)
), so I get debug logging in development and no debug logging in production.Is this the oldest news ever? I've been obsessed with reducing my third-party deps lately, so when it came to logging I was like "Y U NO console.whatever()?"
This even includes a little
logger.log()
helper, but half the time I forget it's there and justconsole.warn()
orconsole.error()
and ITSFINE.GIF. Anyway, hopefully someone will sanity check me and explain why I really can't get away with a <50 LOC vanilla JS logger, LOL.