Skip to content

Instantly share code, notes, and snippets.

@rw3iss
Last active December 16, 2021 01:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rw3iss/47cdfb7730e1577e732a4bfc9f27d549 to your computer and use it in GitHub Desktop.
Save rw3iss/47cdfb7730e1577e732a4bfc9f27d549 to your computer and use it in GitHub Desktop.
Logging by namespace
/* Usage:
import { getLogger } from 'lib/utils/logging';
const log = getLogger('somename').log;
log('something');
*/
let loggers = {};
// retrieve a logger by name.
export const getLogger = function(namespace = '', color = DEFAULT_LOG_COLOR, enabled = true) {
let l = loggers[namespace];
if (!l) {
l = new Logger(namespace, color, enabled);
}
loggers[namespace] = l;
return l;
}
// debugs logs/arguments to a specific namespace (first parameter), or default.
export const log = function(...args) {
const namespace = args.length > 1 ? args[0] : '';
args = args.length > 1 ? args.slice(1, args.length) : [];
let l = getLogger(namespace);
if (l && l.enabled && process.env.IS_DEBUG == 'true') {
let la = [...args];
if (namespace) {
la.unshift(`${colorMap[l.color]}${namespace}:${colorMap['reset']}`);
}
console.log.apply(console, la);
}
}
export const colorMap = {
'reset': '\x1b[0m',
'black': '\x1b[30m',
'red': '\x1b[31m',
'green': '\x1b[32m',
'yellow': '\x1b[33m',
'blue': '\x1b[34m',
'magenta': '\x1b[35m',
'cyan': '\x1b[36m',
'white': '\x1b[37m'
}
export const DEFAULT_LOG_COLOR = 'yellow';
export const IS_DEV = () => {
return process.env.NODE_ENV != 'production';
}
export class Logger {
namespace = '';
color = 'yellow';
enabled = true;
public constructor(namespace, color = DEFAULT_LOG_COLOR, enabled = true) {
this.namespace = namespace;
this.color = color;
this.enabled = enabled;
}
public log = (...args) => {
if (this.enabled) {
log(this.namespace, ...args);
}
return this;
}
public setEnabled(enabled) {
this.enabled = enabled;
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment