Created
July 15, 2020 06:47
-
-
Save Aidurber/d365e6d7ec50c880530a1bdffdd4ff55 to your computer and use it in GitHub Desktop.
A simple logger
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
interface ILogger { | |
log(...args: any[]): void | |
error(...args: any[]): void | |
info(...args: any[]): void | |
warn(...args: any[]): void | |
} | |
type Level = 'log' | 'info' | 'warn' | 'error' | |
const getColor = (level: Level) => { | |
switch (level) { | |
case 'info': | |
return 'color: #03a5fc' | |
case 'error': | |
return 'color: #fc033d' | |
case 'warn': | |
return 'color: #fcb503' | |
case 'log': | |
default: | |
return 'color: #fff' | |
} | |
} | |
class Logger implements ILogger { | |
protected name: string | |
constructor(name: string) { | |
this.name = name | |
} | |
protected withMessage = (level: Level, ...args: any[]) => { | |
const [message, ...rest] = args | |
return [`%c[${this.name}] ${message}`, getColor(level), ...rest] | |
} | |
log(...args: any[]) { | |
console.log(...this.withMessage('log', ...args)) | |
} | |
warn(...args: any[]) { | |
console.warn(...this.withMessage('warn', ...args)) | |
} | |
error(...args: any[]) { | |
console.error(...this.withMessage('error', ...args)) | |
} | |
info(...args: any[]) { | |
console.info(...this.withMessage('info', ...args)) | |
} | |
} | |
class ProductionLogger implements ILogger { | |
// eslint-disable-next-line @typescript-eslint/no-useless-constructor | |
constructor(name: string) {} | |
log(...args: any[]): void { | |
// noop | |
} | |
error(...args: any[]): void { | |
// noop | |
} | |
info(...args: any[]): void { | |
// noop | |
} | |
warn(...args: any[]): void { | |
// noop | |
} | |
} | |
export default process.env.NODE_ENV === 'development' ? Logger : ProductionLogger |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment