Created
October 21, 2024 14:26
-
-
Save SXHRYU/b6232c9f761efb71ff83ea6d92648a3e to your computer and use it in GitHub Desktop.
Logging with multiple handlers to different output, formatters
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 | |
from logging.handlers import HTTPHandler as HTTPLoggingHandler | |
from typing import Any | |
class ExternalFilter(logging.Filter): | |
flag = "to_external_source" | |
def filter(self, record: logging.LogRecord) -> bool: | |
return getattr(record, self.flag, False) | |
class ExternalHTTPLogHandler(HTTPLoggingHandler): | |
def mapLogRecord(self, record: logging.LogRecord) -> dict[str, Any]: | |
return { | |
"query_param_1": "value_1", | |
"text": record.msg, | |
} | |
http_handler = ExternalHTTPLoggingHandler( | |
"host without `http(s)://` and without extra slashes", | |
"url with slashes" | |
secure=True, | |
) | |
http_handler.addFilter(ExternalFilter()) | |
console_handler = logging.StreamHandler() | |
logger = logging.getLogger(__name__) | |
logger.setLevel(logging.DEBUG) | |
logger.addHandler(http_handler) | |
logger.addHandler(console_handler) | |
logger.debug("debug to console") | |
logger.info("info to console & http", extra={ExternalFilter.flag: True}) | |
logger.warning("warning to console & http", extra={ExternalFilter.flag: True}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment