Skip to content

Instantly share code, notes, and snippets.

@rebolyte
Created September 25, 2020 16:38
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 rebolyte/1a39fecd4d1cfb240db34677eef3d71c to your computer and use it in GitHub Desktop.
Save rebolyte/1a39fecd4d1cfb240db34677eef3d71c to your computer and use it in GitHub Desktop.
export type LogLevel = 'error' | 'warn' | 'info' | 'debug';
export interface LoggerOpts {
level: LogLevel;
}
export type LogMethods = {
[key in LogLevel]: (...messages: any) => void;
};
export const createLogger = ({ level = 'info' }: LoggerOpts): LogMethods => {
const levels = {
error: 0,
warn: 1,
info: 2,
debug: 4,
};
// TODO: handle console.dir, console.table, console.assert, etc
const methods = {
error: 'error',
warn: 'warn',
info: 'log',
debug: 'debug',
};
const log = (method: LogLevel, ...messages: any) => {
const rank = levels[method];
const mappedMethod = methods[method];
const displayLevel = `[${method.toUpperCase()}]`;
if (levels[level] >= rank) {
// eslint-disable-next-line no-console
console[mappedMethod](displayLevel, ...messages);
}
};
const shortcuts = Object.keys(methods).reduce<LogMethods>(
(acc, method) => ({
...acc,
[method]: (...messages) => log(method as LogLevel, ...messages),
}),
{} as any,
);
return shortcuts;
};
export const log = createLogger({
level: (window.localStorage.getItem('LOG_LEVEL') as any) || 'error',
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment