Skip to content

Instantly share code, notes, and snippets.

@ermish
Created June 25, 2021 10:07
Show Gist options
  • Save ermish/4e95661730deb0d63d0c102c4c02c6e4 to your computer and use it in GitHub Desktop.
Save ermish/4e95661730deb0d63d0c102c4c02c6e4 to your computer and use it in GitHub Desktop.
Simple js logger
const createLogger = () => {
console.log("made it");
const isProdMode =
process.env.NODE_ENV === "prod" || process.env.NODE_ENV === "production"
? true
: false;
//TODO: move this var to env file or a parameter
// level 1 = debug
// level 2 = default
// level 3 = no logging
let logLevel = 2;
if (isProdMode) {
return createProdLogger(logLevel);
}
return createDevLogger(logLevel);
};
const createProdLogger = (logLevel) => {
//TODO: read your log destination from an env file or add as a parameter.
const debugLogFunction = (message) => {
if (logLevel > 1) return;
const currentTime = new Date().toLocaleTimeString();
console.log(`${currentTime}: ${message}`);
};
const infoLogFunction = (message) => {
if (logLevel > 2) return;
const currentTime = new Date().toLocaleTimeString();
console.log(`${currentTime}: ${message}`);
};
const warnLogFunction = (message) => {
if (logLevel > 2) return;
const currentTime = new Date().toLocaleTimeString();
console.log(`${currentTime}: ${message}`);
};
const errorLogFunction = (message, error) => {
if (logLevel > 2) return;
const currentTime = new Date().toLocaleTimeString();
const fullErrorMessage = error
? message + `\n actual error: ${error.message} \n ${error.stack}`
: message;
console.log(`${currentTime}: ${fullErrorMessage}`);
};
return {
debug: debugLogFunction,
info: infoLogFunction,
warn: warnLogFunction,
error: errorLogFunction,
};
};
const createDevLogger = (logLevel) => {
const debugLogFunction = (message) => {
if (logLevel > 1) return;
const currentTime = new Date().toLocaleTimeString();
console.log(`${currentTime}: ${message}`);
};
const infoLogFunction = (message) => {
if (logLevel > 2) return;
const currentTime = new Date().toLocaleTimeString();
console.log(`${currentTime}: ${message}`);
};
const warnLogFunction = (message) => {
if (logLevel > 2) return;
const currentTime = new Date().toLocaleTimeString();
console.log(`${currentTime}: ${message}`);
};
const errorLogFunction = (message, error) => {
if (logLevel > 2) return;
const currentTime = new Date().toLocaleTimeString();
const fullErrorMessage = error
? message + `\n actual error: ${error.message} \n ${error.stack}`
: message;
console.log(`${currentTime}: ${fullErrorMessage}`);
};
return {
debug: debugLogFunction,
info: infoLogFunction,
warn: warnLogFunction,
error: errorLogFunction,
};
};
let loggerSingleton;
const logger = loggerSingleton ? loggerSingleton : createLogger();
export default logger;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment