Skip to content

Instantly share code, notes, and snippets.

@SXHRYU
Created October 21, 2024 14:26
Show Gist options
  • Save SXHRYU/b6232c9f761efb71ff83ea6d92648a3e to your computer and use it in GitHub Desktop.
Save SXHRYU/b6232c9f761efb71ff83ea6d92648a3e to your computer and use it in GitHub Desktop.
Logging with multiple handlers to different output, formatters
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