Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions src/openai/_utils/_logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@


SENSITIVE_HEADERS = {"api-key", "authorization", "x-amz-security-token"}
_LOG_LEVELS = {
"debug": logging.DEBUG,
"info": logging.INFO,
"warning": logging.WARNING,
"error": logging.ERROR,
"critical": logging.CRITICAL,
}


def _basic_config() -> None:
Expand All @@ -29,12 +36,15 @@ def setup_logging() -> None:
# Transport loggers may include complete URLs. Leave their configuration to
# the application instead of enabling them with the SDK's logging switch.
env = os.environ.get("OPENAI_LOG")
if env == "debug":
_basic_config()
logger.setLevel(logging.DEBUG)
elif env == "info":
_basic_config()
logger.setLevel(logging.INFO)
if env is None:
return

level = _LOG_LEVELS.get(env)
if level is None:
return

_basic_config()
logger.setLevel(level)


class SensitiveHeadersFilter(logging.Filter):
Expand All @@ -45,4 +55,4 @@ def filter(self, record: logging.LogRecord) -> bool:
for header in headers:
if str(header).lower() in SENSITIVE_HEADERS:
headers[header] = "<redacted>"
return True
return True
33 changes: 33 additions & 0 deletions tests/test_log_levels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from __future__ import annotations

import logging

import pytest

from openai._utils._logs import setup_logging


@pytest.mark.parametrize(
("setting", "expected_level"),
[
("debug", logging.DEBUG),
("info", logging.INFO),
("warning", logging.WARNING),
("error", logging.ERROR),
("critical", logging.CRITICAL),
],
)
def test_openai_log_sets_standard_log_level(
setting: str,
expected_level: int,
monkeypatch: pytest.MonkeyPatch,
) -> None:
logger = logging.getLogger("openai")
original_level = logger.level

try:
monkeypatch.setenv("OPENAI_LOG", setting)
setup_logging()
assert logger.level == expected_level
finally:
logger.setLevel(original_level)