Skip to content

Instantly share code, notes, and snippets.

@karpolan
Last active October 7, 2022 01:24
Show Gist options
  • Save karpolan/d27190f2348935b52eff6fc48c69ed39 to your computer and use it in GitHub Desktop.
Save karpolan/d27190f2348935b52eff6fc48c69ed39 to your computer and use it in GitHub Desktop.
Simply logger for React App using TypeScript
const LOG_LEVEL_FROM_ENV = process?.env?.REACT_APP_LOG_LEVEL ?? 'silent';
/**
* Supported logging levels by names, the index is the level number.
*/
export const LOG_LEVEL_NAMES = ['trace', 'debug', 'info', 'warn', 'error', 'silent'];
/**
* Lightweight logger with minimal log level restrictions
* @class Log
*/
class Log {
private readonly _level: number;
constructor(private readonly _name: string) {
this._level = Log.levelNameToLevelNumber(_name);
}
static levelNameToLevelNumber(levelName: string = LOG_LEVEL_FROM_ENV): number {
return LOG_LEVEL_NAMES.indexOf(levelName?.toLowerCase());
}
get level() {
return this._level;
}
get name() {
return this._name;
}
public notify(logLevel: string, ...args: unknown[]): void {
const level = Log.levelNameToLevelNumber(logLevel);
if (level < this._level) {
return; // We don't need to notify or log anything
}
/* eslint-disable no-console */
switch (level) {
case 0: // trace
console.trace(...args);
break;
case 1: // debug
console.debug(...args);
break;
case 2: // info
console.info(...args);
break;
case 3: // warn
console.warn(...args);
break;
case 4: // error
console.error(...args);
break;
case 5: // critical
console.error(...args);
break;
default:
// Do nothing
break;
}
/* eslint-enable no-console */
}
public trace(...args: unknown[]): void {
this.notify(LOG_LEVEL_NAMES[0], ...args);
}
public debug(...args: unknown[]): void {
this.notify(LOG_LEVEL_NAMES[1], ...args);
}
public info(...args: unknown[]): void {
this.notify(LOG_LEVEL_NAMES[2], ...args);
}
public warn(...args: unknown[]): void {
this.notify(LOG_LEVEL_NAMES[3], ...args);
}
public error(...args: unknown[]): void {
this.notify(LOG_LEVEL_NAMES[4], ...args);
}
public critical(...args: unknown[]): void {
this.notify(LOG_LEVEL_NAMES[5], ...args);
}
public log(...args: unknown[]): void {
this.notify(this._name, ...args);
}
}
export const log = new Log(LOG_LEVEL_FROM_ENV);
// eslint-disable-next-line no-console
console.log(`Log level: ${log.level} aka "${log.name}"`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment