Created
August 10, 2023 09:16
-
-
Save atemate/37ee0225d42ed8206976aefb76bb7df3 to your computer and use it in GitHub Desktop.
Configure python logging to stderr only
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import os | |
import sys | |
from distutils.util import strtobool | |
from typing import Optional | |
def configure_logging_to_stderr_only(filename: Optional[str] = None): | |
"""Configures a basic config depending on 'DEBUG' env variable, | |
and also re-configures all existing handlers to output to stderr | |
(so that our program can solely use stdout). | |
""" | |
logger = logging.getLogger(filename) | |
kwargs = {} | |
is_debug = bool(strtobool(os.environ.get("DEBUG") or "false")) | |
kwargs["level"] = logging.DEBUG if is_debug else logging.INFO | |
kwargs["stream"] = sys.stderr | |
logging.basicConfig(**kwargs) | |
# Resetting all existing handlers to stderr | |
for logger_name in logging.root.manager.loggerDict: | |
lgr = logging.getLogger(logger_name) | |
for hdl in lgr.handlers: | |
if isinstance(hdl, logging.StreamHandler) and hdl.stream != sys.stderr: | |
lgr.removeHandler(hdl) | |
hdl.setStream(sys.stderr) | |
lgr.addHandler(hdl) | |
logging.debug(f"Redirected log handler to stderr: {lgr.name}") | |
return logger |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment