_logs.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import os
  2. import logging
  3. from typing_extensions import override
  4. from ._utils import is_dict
  5. logger: logging.Logger = logging.getLogger("openai")
  6. httpx_logger: logging.Logger = logging.getLogger("httpx")
  7. SENSITIVE_HEADERS = {"api-key", "authorization"}
  8. def _basic_config() -> None:
  9. # e.g. [2023-10-05 14:12:26 - openai._base_client:818 - DEBUG] HTTP Request: POST http://127.0.0.1:4010/foo/bar "200 OK"
  10. logging.basicConfig(
  11. format="[%(asctime)s - %(name)s:%(lineno)d - %(levelname)s] %(message)s",
  12. datefmt="%Y-%m-%d %H:%M:%S",
  13. )
  14. def setup_logging() -> None:
  15. env = os.environ.get("OPENAI_LOG")
  16. if env == "debug":
  17. _basic_config()
  18. logger.setLevel(logging.DEBUG)
  19. httpx_logger.setLevel(logging.DEBUG)
  20. elif env == "info":
  21. _basic_config()
  22. logger.setLevel(logging.INFO)
  23. httpx_logger.setLevel(logging.INFO)
  24. class SensitiveHeadersFilter(logging.Filter):
  25. @override
  26. def filter(self, record: logging.LogRecord) -> bool:
  27. if is_dict(record.args) and "headers" in record.args and is_dict(record.args["headers"]):
  28. headers = record.args["headers"] = {**record.args["headers"]}
  29. for header in headers:
  30. if str(header).lower() in SENSITIVE_HEADERS:
  31. headers[header] = "<redacted>"
  32. return True