1# SPDX-License-Identifier: MIT OR Apache-2.0
2# This file is dual licensed under the terms of the Apache License, Version
3# 2.0, and the MIT License. See the LICENSE file in the root of this
4# repository for complete details.
5
6"""
7Extracted log level data used by both stdlib and native log level filters.
8"""
9
10from __future__ import annotations
11
12from typing import Any
13
14from .typing import EventDict
15
16
17# Adapted from the stdlib
18CRITICAL = 50
19FATAL = CRITICAL
20ERROR = 40
21WARNING = 30
22WARN = WARNING
23INFO = 20
24DEBUG = 10
25NOTSET = 0
26
27NAME_TO_LEVEL = {
28 "critical": CRITICAL,
29 "exception": ERROR,
30 "error": ERROR,
31 "warn": WARNING,
32 "warning": WARNING,
33 "info": INFO,
34 "debug": DEBUG,
35 "notset": NOTSET,
36}
37
38LEVEL_TO_NAME = {
39 v: k
40 for k, v in NAME_TO_LEVEL.items()
41 if k not in ("warn", "exception", "notset")
42}
43
44# Keep around for backwards-compatability in case someone imported them.
45_LEVEL_TO_NAME = LEVEL_TO_NAME
46_NAME_TO_LEVEL = NAME_TO_LEVEL
47
48
49def map_method_name(method_name: str) -> str:
50 # warn is just a deprecated alias in the stdlib.
51 if method_name == "warn":
52 return "warning"
53
54 # Calling exception("") is the same as error("", exc_info=True)
55 if method_name == "exception":
56 return "error"
57
58 return method_name
59
60
61def add_log_level(
62 logger: Any, method_name: str, event_dict: EventDict
63) -> EventDict:
64 """
65 Add the log level to the event dict under the ``level`` key.
66
67 Since that's just the log method name, this processor works with non-stdlib
68 logging as well. Therefore it's importable both from `structlog.processors`
69 as well as from `structlog.stdlib`.
70
71 .. versionadded:: 15.0.0
72 .. versionchanged:: 20.2.0
73 Importable from `structlog.processors` (additionally to
74 `structlog.stdlib`).
75 .. versionchanged:: 24.1.0
76 Added mapping from "exception" to "error"
77 """
78
79 event_dict["level"] = map_method_name(method_name)
80
81 return event_dict