All files / log / levels.ts

100.00% Branches 4/4
100.00% Lines 32/32
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
 
 
 
 
 
 
 
 
 
x86
x86
x86
x86
x86
x86
x86
x86
 
 
 
 
 
 
 
 
x86
x86
 
 
x86
x86
x86
x86
x86
x86
x86
x86
 
 
 
 
 
x86
x335
x335
x583
x583
x336
x335
 
 
x86
x582
x582
x1077
x1077
x583
x582
























































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

/**
 * Use this to retrieve the numeric log level by it's associated name.
 * Defaults to INFO.
 *
 * @internal
 */
export const LogLevels = {
  NOTSET: 0,
  DEBUG: 10,
  INFO: 20,
  WARN: 30,
  ERROR: 40,
  CRITICAL: 50,
} as const;

/** Union of valid log levels */
export type LogLevel = typeof LogLevels[LevelName];

/** Union of valid log level names */
export type LevelName = Exclude<keyof typeof LogLevels, number>;

/** Permitted log level names */
export const LogLevelNames: LevelName[] = Object.keys(LogLevels).filter((key) =>
  isNaN(Number(key))
) as LevelName[];

const byLevel: Record<LogLevel, LevelName> = {
  [LogLevels.NOTSET]: "NOTSET",
  [LogLevels.DEBUG]: "DEBUG",
  [LogLevels.INFO]: "INFO",
  [LogLevels.WARN]: "WARN",
  [LogLevels.ERROR]: "ERROR",
  [LogLevels.CRITICAL]: "CRITICAL",
};

/**
 * Returns the numeric log level associated with the passed,
 * stringy log level name.
 */
export function getLevelByName(name: LevelName): LogLevel {
  const level = LogLevels[name];
  if (level !== undefined) {
    return level;
  }
  throw new Error(`Cannot get log level: no level named ${name}`);
}

/** Returns the stringy log level name provided the numeric log level. */
export function getLevelName(level: LogLevel): LevelName {
  const levelName = byLevel[level as LogLevel];
  if (levelName) {
    return levelName;
  }
  throw new Error(`Cannot get log level: no name for level: ${level}`);
}