Skip to content

Instantly share code, notes, and snippets.

@calebhailey
Last active March 22, 2023 02:35
Show Gist options
  • Save calebhailey/ef15c0248ba826615038ed755f43a394 to your computer and use it in GitHub Desktop.
Save calebhailey/ef15c0248ba826615038ed755f43a394 to your computer and use it in GitHub Desktop.
// 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;
@calebhailey
Copy link
Author

calebhailey commented Mar 22, 2023

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 running logger.setLogLevel("warn") gives me a one-liner for "muting" any rogue console.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 just console.warn() or console.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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment