Permalink
Fetching contributors…
Cannot retrieve contributors at this time
121 lines (106 sloc) 2.65 KB
import { debuglog } from "util"
export type Log = (message: string, ...optionalParams: any[]) => void
/**
* Simple interface for logging.
*/
export interface Logger {
trace: Log
debug: Log
info: Log
warn: Log
error: Log
}
export const LogLevels: (keyof Logger)[] = [
"trace",
"debug",
"info",
"warn",
"error"
]
const _debuglog = debuglog("batch-cluster")
const noop = () => undefined
/**
* Default `Logger` implementation. `debug` and `info` go to
* util.debuglog("batch-cluster")`. `warn` and `error` go to `console.warn` and
* `console.error`.
*/
export const ConsoleLogger: Logger = Object.freeze({
/**
* No-ops by default, as this is very low-level information.
*/
trace: noop,
/**
* Delegates to `util.debuglog("batch-cluster")`:
* <https://nodejs.org/api/util.html#util_util_debuglog_section>
*/
debug: _debuglog,
/**
* Delegates to `util.debuglog("batch-cluster")`:
* <https://nodejs.org/api/util.html#util_util_debuglog_section>
*/
info: _debuglog,
/**
* Delegates to `console.warn`
*/
warn: console.warn,
/**
* Delegates to `console.error`
*/
error: console.error
})
/**
* `Logger` that disables all logging.
*/
export const NoLogger: Logger = Object.freeze({
trace: noop,
debug: noop,
info: noop,
warn: noop,
error: noop
})
let _logger: Logger = NoLogger
export function setLogger(l: Logger) {
if (LogLevels.some(ea => typeof l[ea] !== "function")) {
throw new Error("invalid logger, must implement " + LogLevels)
}
_logger = l
}
export function logger() {
return _logger
}
export namespace Logger {
export function withLevels(delegate: Logger): Logger {
const timestamped: any = {}
LogLevels.forEach(ea => {
const prefix = (ea + " ").substring(0, 5) + " | "
timestamped[ea] = (message?: any, ...optionalParams: any[]) =>
message != null && delegate[ea](prefix + message, ...optionalParams)
})
return timestamped
}
export function withTimestamps(delegate: Logger): Logger {
const timestamped: any = {}
LogLevels.forEach(
ea =>
(timestamped[ea] = (message?: any, ...optionalParams: any[]) =>
message != null &&
delegate[ea](
new Date().toISOString() + " | " + message,
...optionalParams
))
)
return timestamped
}
export function filterLevels(
logger: Logger,
minLogLevel: keyof Logger
): Logger {
const minLogLevelIndex = LogLevels.indexOf(minLogLevel)
const filtered: any = {}
LogLevels.forEach(
(ea, idx) =>
(filtered[ea] = idx < minLogLevelIndex ? noop : logger[ea].bind(logger))
)
return filtered
}
}