diff options
author | Sebastian <sebasjm@gmail.com> | 2021-08-23 16:46:06 -0300 |
---|---|---|
committer | Sebastian <sebasjm@gmail.com> | 2021-08-23 16:48:30 -0300 |
commit | 38acabfa6089ab8ac469c12b5f55022fb96935e5 (patch) | |
tree | 453dbf70000cc5e338b06201af1eaca8343f8f73 /@linaria/packages/logger/src/index.ts | |
parent | f26125e039143b92dc0d84e7775f508ab0cdcaa8 (diff) | |
download | node-vendor-38acabfa6089ab8ac469c12b5f55022fb96935e5.tar.gz node-vendor-38acabfa6089ab8ac469c12b5f55022fb96935e5.tar.bz2 node-vendor-38acabfa6089ab8ac469c12b5f55022fb96935e5.zip |
Diffstat (limited to '@linaria/packages/logger/src/index.ts')
-rw-r--r-- | @linaria/packages/logger/src/index.ts | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/@linaria/packages/logger/src/index.ts b/@linaria/packages/logger/src/index.ts new file mode 100644 index 0000000..45765bb --- /dev/null +++ b/@linaria/packages/logger/src/index.ts @@ -0,0 +1,63 @@ +import genericDebug from 'debug'; +import type { Debugger } from 'debug'; + +type LogLevel = 'error' | 'warn' | 'info' | 'debug'; + +const levels = ['error', 'warn', 'info', 'debug']; +const currentLevel = levels.indexOf(process.env.LINARIA_LOG || 'error'); + +const linariaLogger = genericDebug('linaria'); + +const loggers = new Map<string, Debugger>(); + +function gerOrCreate(namespace: string | null | undefined): Debugger { + if (!namespace) return linariaLogger; + const lastIndexOf = namespace.lastIndexOf(':'); + if (!loggers.has(namespace)) { + loggers.set( + namespace, + gerOrCreate(namespace.substr(0, lastIndexOf)).extend( + namespace.substr(lastIndexOf + 1) + ) + ); + } + + return loggers.get(namespace)!; +} + +const format = <T>(text: T) => { + if (typeof text === 'string') { + return text.replace(/\n/g, '\n\t'); + } + + return text; +}; + +function log( + level: LogLevel, + namespaces: string, + arg1: any | (() => void), + ...restArgs: any[] +) { + if (currentLevel < levels.indexOf(level)) { + return; + } + + const logger = gerOrCreate(namespaces); + if (!logger.enabled) return; + + if (typeof arg1 === 'function') { + const text = arg1(); + if (text) { + logger('', format(text), ...restArgs); + } + return; + } + + logger('', format(arg1), ...restArgs); +} + +export const debug = log.bind(null, 'debug'); +export const info = log.bind(null, 'info'); +export const warn = log.bind(null, 'warn'); +export const error = log.bind(null, 'error'); |