Coverage for app / util / logger.py: 100%

61 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1"""How the service logs: its own code at ``LOG_LEVEL``, every library at WARNING. 

2 

3The root logger used to be at DEBUG, so every library logged everything it 

4does, in production too: botocore each request's body and its session token, 

5langchain-aws and LiteLLM each prompt and reply, SQLAlchemy each statement 

6with its parameters. A person's words went to the container log and from 

7there to Loki. Now the root logger — every library that sets no level of its 

8own — is at WARNING, so a library's warnings and errors still show and its 

9working does not. The service's own loggers are all under ``app`` 

10(``APP_LOGGER``), at ``LOG_LEVEL`` (INFO by default), and log sizes and ids, 

11never content. ``LITELLM_DEBUG`` remains the one opt-in for a library's 

12payloads, for a developer, by hand. ``tests/test_logging.py`` holds all of it. 

13""" 

14 

15import logging 

16import os 

17import sys 

18from colorlog import ColoredFormatter, escape_codes 

19 

20 

21class XColorFormatter(ColoredFormatter): 

22 NAME_COLORS = { 

23 "uvicorn.access": "cyan", 

24 "uvicorn.error": "red", 

25 "uvicorn": "blue", 

26 "alembic": "yellow", 

27 "pymongo": "yellow", 

28 "app": "green", 

29 } 

30 

31 def format(self, record): 

32 color = "white" 

33 for prefix, c in self.NAME_COLORS.items(): 

34 if record.name.startswith(prefix): 

35 color = c 

36 break 

37 

38 record.name_color = escape_codes.escape_codes.get(color, "") 

39 return super().format(record) 

40 

41 

42formatter = XColorFormatter( 

43 fmt=( 

44 "%(log_color)s%(asctime)s | " 

45 "%(levelname)s%(reset)s | " 

46 "%(name_color)s%(name)s%(reset)s | " 

47 "%(message)s" 

48 ), 

49 datefmt="%Y-%m-%d %H:%M:%S", 

50 log_colors={ 

51 "DEBUG": "thin_white", # <-- FIXED 

52 "INFO": "green", 

53 "WARNING": "yellow", 

54 "ERROR": "red", 

55 "CRITICAL": "bold_red", 

56 }, 

57) 

58 

59 

60class MaxLevelFilter(logging.Filter): 

61 def __init__(self, max_level): 

62 self.max_level = max_level 

63 

64 def filter(self, record): 

65 return record.levelno < self.max_level 

66 

67 

68stdout_handler = logging.StreamHandler(sys.stdout) 

69stdout_handler.setLevel(logging.DEBUG) 

70stdout_handler.addFilter(MaxLevelFilter(logging.WARNING)) 

71stdout_handler.setFormatter(formatter) 

72 

73stderr_handler = logging.StreamHandler(sys.stderr) 

74stderr_handler.setLevel(logging.WARNING) 

75stderr_handler.setFormatter(formatter) 

76 

77handlers = [stdout_handler, stderr_handler] 

78 

79#: Every logger the service's own code names is under this one, so one level 

80#: governs all of them. 

81APP_LOGGER = "app" 

82#: Where every library's logging stops (see the module notes). 

83LIBRARY_LEVEL = logging.WARNING 

84 

85 

86def app_level() -> int: 

87 """``LOG_LEVEL`` as a level: INFO when unset or not a level's name.""" 

88 level = logging.getLevelName(os.environ.get("LOG_LEVEL", "INFO").strip().upper()) 

89 return level if isinstance(level, int) else logging.INFO 

90 

91 

92root_logger = logging.getLogger() 

93root_logger.setLevel(LIBRARY_LEVEL) 

94root_logger.handlers.clear() 

95root_logger.handlers.extend(handlers) 

96logging.getLogger(APP_LOGGER).setLevel(app_level()) 

97 

98#: Python's warnings — a library's deprecation, pydantic's serializer 

99#: warnings — become WARNING records on ``py.warnings``, with a timestamp and 

100#: a level. They used to go to stderr bare, over several lines that Grafana 

101#: showed as separate entries with no level. 

102logging.captureWarnings(True) 

103 

104 

105for name in ("uvicorn", "uvicorn.error", "uvicorn.access"): 

106 logger = logging.getLogger(name) 

107 logger.handlers.clear() 

108 logger.handlers.extend(handlers) 

109 logger.setLevel(logging.INFO) 

110 logger.propagate = False 

111 

112 

113for name in ("alembic", "pymongo"): 

114 logger = logging.getLogger(name) 

115 logger.setLevel(logging.INFO) 

116 logger.propagate = True 

117 

118 

119# --------------------------------------------------------------------------- 

120# Correlation ID — propagated per asyncio task (one ContextVar per request) 

121# --------------------------------------------------------------------------- 

122 

123import contextvars # noqa: E402 

124 

125_correlation_id: contextvars.ContextVar[str] = contextvars.ContextVar( 

126 "correlation_id", default="" 

127) 

128 

129 

130def set_correlation_id(cid: str) -> None: 

131 """Set the correlation ID for the current asyncio task.""" 

132 _correlation_id.set(cid) 

133 

134 

135def get_correlation_id() -> str: 

136 """Return the correlation ID for the current asyncio task, or '' if unset.""" 

137 return _correlation_id.get() 

138 

139 

140class CorrelationLogAdapter(logging.LoggerAdapter): 

141 """Prepends the active correlation ID to every log message.""" 

142 

143 def process(self, msg: str, kwargs: dict) -> tuple[str, dict]: 

144 cid = get_correlation_id() 

145 return (f"[{cid}] {msg}" if cid else msg, kwargs) 

146 

147 

148def get_logger(name: str) -> CorrelationLogAdapter: 

149 """Return a logger that automatically injects the current correlation ID.""" 

150 return CorrelationLogAdapter(logging.getLogger(name), {})