All files / log / setup.ts

33.33% Branches 2/6
88.24% Lines 30/34
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
 
 
 
 
x33
x33
x33
 
 
x33
x89
x356
x356
x89
 
 
x89
x118
x89
x89
 
 
 
 
x89
x159
x159
x159
 
 
x89
 
 
 
x89
 
x151
 
x151
x214
x214
x214
x214
x151
 
 
x453
x151
x151
x89
 
x33





















I










I

I









I





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

import type { BaseHandler } from "./base_handler.ts";
import { DEFAULT_CONFIG, DEFAULT_LEVEL } from "./_config.ts";
import { type LogConfig, Logger } from "./logger.ts";
import { state } from "./_state.ts";

/** Setup logger config. */
export function setup(config: LogConfig) {
  state.config = {
    handlers: { ...DEFAULT_CONFIG.handlers, ...config.handlers },
    loggers: { ...DEFAULT_CONFIG.loggers, ...config.loggers },
  };

  // tear down existing handlers
  state.handlers.forEach((handler) => {
    handler.destroy();
  });
  state.handlers.clear();

  // setup handlers
  const handlers = state.config.handlers ?? {};

  for (const [handlerName, handler] of Object.entries(handlers)) {
    handler.setup();
    state.handlers.set(handlerName, handler);
  }

  // remove existing loggers
  state.loggers.clear();

  // setup loggers
  const loggers = state.config.loggers ?? {};
  for (const [loggerName, loggerConfig] of Object.entries(loggers)) {
    const handlerNames = loggerConfig.handlers ?? [];
    const handlers: BaseHandler[] = [];

    handlerNames.forEach((handlerName) => {
      const handler = state.handlers.get(handlerName);
      if (handler) {
        handlers.push(handler);
      }
    });

    const levelName = loggerConfig.level ?? DEFAULT_LEVEL;
    const logger = new Logger(loggerName, levelName, { handlers: handlers });
    state.loggers.set(loggerName, logger);
  }
}

setup(DEFAULT_CONFIG);