Created
September 25, 2020 16:38
-
-
Save rebolyte/1a39fecd4d1cfb240db34677eef3d71c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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