Skip to content

Instantly share code, notes, and snippets.

@calebhailey
Last active July 23, 2024 18:44
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;
@RaviGhaghada
Copy link

RaviGhaghada commented Jul 23, 2024

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