diff options
author | Christopher Dieringer <cdaringe@users.noreply.github.com> | 2020-04-25 02:13:26 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-04-25 11:13:26 +0200 |
commit | b28e60ecaf5d48c36cb435361834f4884d9451c2 (patch) | |
tree | bc4fd6aa37ba3cd931ff29d259a05f8126202f34 /std/log/levels.ts | |
parent | f8d83361cd11d3aa42333171ecb6b129fdcbefeb (diff) |
refactor(std/log): support enum log level (#4859)
Diffstat (limited to 'std/log/levels.ts')
-rw-r--r-- | std/log/levels.ts | 71 |
1 files changed, 52 insertions, 19 deletions
diff --git a/std/log/levels.ts b/std/log/levels.ts index be960dd57..ed6010ba2 100644 --- a/std/log/levels.ts +++ b/std/log/levels.ts @@ -1,26 +1,59 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -export const LogLevel: Record<string, number> = { - NOTSET: 0, - DEBUG: 10, - INFO: 20, - WARNING: 30, - ERROR: 40, - CRITICAL: 50, -}; +/** Get log level numeric values through enum constants + */ +export enum LogLevels { + NOTSET = 0, + DEBUG = 10, + INFO = 20, + WARNING = 30, + ERROR = 40, + CRITICAL = 50, +} + +/** Permitted log level names */ +export const LogLevelNames = Object.keys(LogLevels).filter((key) => + isNaN(Number(key)) +); + +/** Union of valid log level strings */ +export type LevelName = keyof typeof LogLevels; -const byLevel = { - [LogLevel.NOTSET]: "NOTSET", - [LogLevel.DEBUG]: "DEBUG", - [LogLevel.INFO]: "INFO", - [LogLevel.WARNING]: "WARNING", - [LogLevel.ERROR]: "ERROR", - [LogLevel.CRITICAL]: "CRITICAL", +const byLevel: Record<string, LevelName> = { + [String(LogLevels.NOTSET)]: "NOTSET", + [String(LogLevels.DEBUG)]: "DEBUG", + [String(LogLevels.INFO)]: "INFO", + [String(LogLevels.WARNING)]: "WARNING", + [String(LogLevels.ERROR)]: "ERROR", + [String(LogLevels.CRITICAL)]: "CRITICAL", }; -export function getLevelByName(name: string): number { - return LogLevel[name]; +/** Returns the numeric log level associated with the passed, + * stringy log level name. + */ +export function getLevelByName(name: LevelName): number { + switch (name) { + case "NOTSET": + return LogLevels.NOTSET; + case "DEBUG": + return LogLevels.DEBUG; + case "INFO": + return LogLevels.INFO; + case "WARNING": + return LogLevels.WARNING; + case "ERROR": + return LogLevels.ERROR; + case "CRITICAL": + return LogLevels.CRITICAL; + default: + throw new Error(`no log level found for "${name}"`); + } } -export function getLevelName(level: number): string { - return byLevel[level]; +/** Returns the stringy log level name provided the numeric log level */ +export function getLevelName(level: number): LevelName { + const levelName = byLevel[level]; + if (levelName) { + return levelName; + } + throw new Error(`no level name found for level: ${level}`); } |