Disable handlers, setup propagation with uvicorn log_config

Apparently this was what I have been chasing for the last few hours.
This commit is contained in:
2024-11-01 14:56:40 -05:00
parent 3a2ef75086
commit 1741739310
3 changed files with 32 additions and 16 deletions

View File

@@ -2,7 +2,6 @@ import sys
import structlog import structlog
logger = structlog.get_logger() logger = structlog.get_logger()
@@ -17,7 +16,15 @@ def main(*args):
run( run(
"linkpulse.app:app", "linkpulse.app:app",
reload=True, reload=True,
host="0.0.0.0" host="0.0.0.0",
log_config={
"version": 1,
"disable_existing_loggers": False,
"loggers": {
"uvicorn": {"propagate": True},
"uvicorn.access": {"propagate": True},
},
},
) )
elif args[0] == "migrate": elif args[0] == "migrate":

View File

@@ -24,7 +24,6 @@ from psycopg2.extras import execute_values
from linkpulse.logging import setup_logging from linkpulse.logging import setup_logging
setup_logging(json_logs=False, log_level="DEBUG")
load_dotenv(dotenv_path=".env") load_dotenv(dotenv_path=".env")
@@ -124,6 +123,7 @@ class IPCounter:
app = FastAPI(lifespan=lifespan) app = FastAPI(lifespan=lifespan)
setup_logging()
if is_development: if is_development:
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware

View File

@@ -1,17 +1,16 @@
import logging import logging
import os
import sys import sys
from typing import List from typing import List, Optional
import structlog import structlog
from structlog.types import EventDict, Processor from structlog.types import EventDict, Processor
from itertools import chain
def rename_event_key(_, __, event_dict: EventDict) -> EventDict: def rename_event_key(_, __, event_dict: EventDict) -> EventDict:
""" """
Renames the `event` key to `msg`, as Railway expects it in that form. Renames the `event` key to `msg`, as Railway expects it in that form.
""" """
print(event_dict)
event_dict["msg"] = event_dict.pop("event") event_dict["msg"] = event_dict.pop("event")
return event_dict return event_dict
@@ -86,17 +85,27 @@ def setup_logging(json_logs: bool = False, log_level: str = "INFO"):
root_logger.addHandler(handler) root_logger.addHandler(handler)
root_logger.setLevel(log_level.upper()) root_logger.setLevel(log_level.upper())
def configure_logger(name: str, clear: bool, propagate: bool) -> None: def configure_logger(name: str, level: Optional[str] = None, clear: Optional[bool] = None, propagate: Optional[bool] = None) -> None:
logger = logging.getLogger(name) logger = logging.getLogger(name)
if clear:
logger.handlers.clear()
logger.propagate = propagate
for _log in ["uvicorn", "uvicorn.error"]: if level is not None:
# Clear the log handlers for uvicorn loggers, and enable propagation logger.setLevel(level.upper())
# so the messages are caught by our root logger and formatted correctly
# by structlog if clear is True:
configure_logger(_log, clear=True, propagate=False) logger.handlers.clear()
if propagate is not None:
logger.propagate = propagate
# Clear the log handlers for uvicorn loggers, and enable propagation
# so the messages are caught by our root logger and formatted correctly
# by structlog
configure_logger("uvicorn", clear=True, propagate=True)
configure_logger("uvicorn.error", clear=True, propagate=True)
configure_logger("apscheduler.executors.default", level="WARNING")
# Since we re-create the access logs ourselves, to add all information # Since we re-create the access logs ourselves, to add all information
# in the structured log (see the `logging_middleware` in main.py), we clear # in the structured log (see the `logging_middleware` in main.py), we clear
@@ -118,4 +127,4 @@ def setup_logging(json_logs: bool = False, log_level: str = "INFO"):
"Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback) "Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback)
) )
sys.excepthook = handle_exception sys.excepthook = handle_exception