Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python

Add LOG_LEVEL env var to control log verbosity (#1142)

wocessadef77fe8581c84
diff --git a/.env.example b/.env.example
index d1c2f0ad..033269e7 100644
--- a/.env.example
+++ b/.env.example
@@ -243,10 +243,15 @@ WEB_FETCH_ALLOWED_SCHEMES=http,https
WEB_FETCH_ALLOW_PRIVATE_NETWORKS=false
-# Structured TRACE logs: lines with `"trace": true` merge ingress/routing/cli/provider/egress
-# stages. Conversation text is logged in those payloads (verbatim). Values under keys named
-# like ``api_key`` / ``authorization`` are redacted. Raw transport payloads still require
-# the LOG_RAW_* toggles below.
+# Structured traces: DEBUG lines with `"trace": true` merge
+# ingress/routing/cli/provider/egress stages. Conversation text is logged in those payloads
+# (verbatim). Values under keys named like ``api_key`` / ``authorization`` are redacted.
+# Raw transport payloads still require the LOG_RAW_* toggles below.
+#
+# Minimum log level for the JSON file sink: DEBUG, INFO, WARNING, ERROR, CRITICAL.
+# Defaults to INFO. Use DEBUG temporarily for detailed request traces, or WARNING for quieter logs.
+# The file rotates at 50 MB and retains five rotated files (roughly 300 MB including the active file).
+LOG_LEVEL=INFO
#
# Verbose diagnostics (avoid logging raw prompts / SSE bodies in production)
DEBUG_PLATFORM_EDITS=false
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index d9642f73..17a9c336 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -1191,6 +1191,11 @@ without requiring raw transport logs by default.
Logging defaults are conservative:
+- The JSON file sink defaults to `INFO`. Detailed structured request traces use
+ `DEBUG`, so normal customer logs retain lifecycle and failure events without
+ recording request-by-request trace payloads.
+- The active server log rotates at 50 MB and retains five rotated files,
+ bounding normal on-disk usage to roughly 300 MB.
- API payloads and SSE events are not logged raw unless explicitly enabled.
- Provider and application errors log metadata by default; verbose traceback and
message logging are opt-in.
diff --git a/pyproject.toml b/pyproject.toml
index c25a96eb..a211fcb4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "free-claude-code"
-version = "4.7.2"
+version = "4.7.3"
description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"
readme = "README.md"
requires-python = ">=3.14.0"
diff --git a/src/free_claude_code/config/logging_config.py b/src/free_claude_code/config/logging_config.py
index dd100fa5..2d1b4ac1 100644
--- a/src/free_claude_code/config/logging_config.py
+++ b/src/free_claude_code/config/logging_config.py
@@ -15,6 +15,19 @@ from pathlib import Path
from loguru import logger
_configured = False
+_current_path: Path | None = None
+_current_level = "INFO"
+_current_verbose: bool | None = None
+_sink_id: int | None = None
+
+_THIRD_PARTY_LOGGERS = (
+ "httpx",
+ "httpcore",
+ "httpcore.http11",
+ "httpcore.connection",
+ "telegram",
+ "telegram.ext",
+)
# Loguru ``logger.bind()`` key used by structured TRACE payloads; ``core/trace.py``
# uses the identical string constant ``TRACE_PAYLOAD_BINDING``.
@@ -104,56 +117,80 @@ class InterceptHandler(logging.Handler):
self._local.active = False
+def _set_third_party_levels(verbose: bool) -> None:
+ level = logging.NOTSET if verbose else logging.WARNING
+ for name in _THIRD_PARTY_LOGGERS:
+ logging.getLogger(name).setLevel(level)
+
+
+def _add_file_sink(log_file: str | Path, level: str) -> int:
+ log_path = Path(log_file)
+ return logger.add(
+ log_path,
+ level=level,
+ format=_serialize_with_context,
+ encoding="utf-8",
+ mode="a",
+ rotation="50 MB",
+ retention=5,
+ enqueue=True,
+ )
+
+
def configure_logging(
- log_file: str | Path, *, force: bool = False, verbose_third_party: bool = False
+ log_file: str | Path,
+ *,
+ force: bool = False,
+ verbose_third_party: bool = False,
+ level: str = "INFO",
) -> None:
"""Configure loguru with JSON output to log_file and intercept stdlib logging.
- Idempotent: skips if already configured (e.g. hot reload).
- Use force=True to reconfigure (e.g. in tests with a different log path).
+ Idempotent: skips if already configured with the same path, level, and verbosity.
+ On path or level change, replaces only the file sink without truncating.
+ On verbosity change alone, updates only the third-party logger levels.
+ Use force=True to reconfigure from scratch.
- When ``verbose_third_party`` is false, noisy HTTP and Telegram loggers are capped
- at WARNING unless explicitly configured otherwise.
+ When ``verbose_third_party`` is false, noisy HTTP and Telegram loggers are
+ capped at WARNING unless explicitly configured otherwise.
"""
- global _configured
- if _configured and not force:
+ global _configured, _current_path, _current_level, _current_verbose, _sink_id
+
+ log_path = Path(log_file).expanduser().resolve()
+ log_path.parent.mkdir(parents=True, exist_ok=True)
+
+ if (
+ _configured
+ and not force
+ and log_path == _current_path
+ and level == _current_level
+ and verbose_third_party == _current_verbose
+ ):
return
- _configured = True
- # Remove default loguru handler (writes to stderr)
- logger.remove()
+ if not _configured or force:
+ _configured = True
- log_path = Path(log_file)
- log_path.parent.mkdir(parents=True, exist_ok=True)
+ logger.remove()
- # Truncate log file on fresh start for clean debugging
- log_path.write_text("")
+ log_path.write_text("")
- # Add file sink: JSON lines, DEBUG level, context vars at top level
- logger.add(
- log_file,
- level="DEBUG",
- format=_serialize_with_context,
- encoding="utf-8",
- mode="a",
- rotation="50 MB",
- enqueue=True,
- )
+ _sink_id = _add_file_sink(log_path, level)
- # Intercept stdlib logging: route all root logger output to loguru
- intercept = InterceptHandler()
- logging.root.handlers = [intercept]
- logging.root.setLevel(logging.DEBUG)
-
- third_party = (
- "httpx",
- "httpcore",
- "httpcore.http11",
- "httpcore.connection",
- "telegram",
- "telegram.ext",
- )
- for name in third_party:
- logging.getLogger(name).setLevel(
- logging.WARNING if not verbose_third_party else logging.NOTSET
- )
+ intercept = InterceptHandler()
+ logging.root.handlers = [intercept]
+ logging.root.setLevel(logging.DEBUG)
+
+ _set_third_party_levels(verbose_third_party)
+ elif log_path != _current_path or level != _current_level:
+ if _sink_id is not None:
+ logger.remove(_sink_id)
+ _sink_id = _add_file_sink(log_path, level)
+ if verbose_third_party != _current_verbose:
+ _set_third_party_levels(verbose_third_party)
+ else:
+ _set_third_party_levels(verbose_third_party)
+
+ _current_path = log_path
+ _current_level = level
+ _current_verbose = verbose_third_party
diff --git a/src/free_claude_code/config/settings.py b/src/free_claude_code/config/settings.py
index 98db0e2c..6681c19d 100644
--- a/src/free_claude_code/config/settings.py
+++ b/src/free_claude_code/config/settings.py
@@ -219,6 +219,8 @@ class Settings(BaseSettings):
)
# ==================== Debug / diagnostic logging (avoid sensitive content) ====================
+ # Minimum log level for the JSON file sink (DEBUG, INFO, WARNING, ERROR, CRITICAL).
+ log_level: str = Field(default="INFO", validation_alias="LOG_LEVEL")
# When false (default), API and SSE helpers log only metadata (counts, lengths, ids).
log_raw_api_payloads: bool = Field(
default=False, validation_alias="LOG_RAW_API_PAYLOADS"
@@ -318,6 +320,15 @@ class Settings(BaseSettings):
return None
return v
+ @field_validator("log_level")
+ @classmethod
+ def validate_log_level(cls, v: str) -> str:
+ valid = {"DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"}
+ upper = v.upper()
+ if upper not in valid:
+ raise ValueError(f"LOG_LEVEL must be one of {sorted(valid)}, got {v!r}")
+ return upper
+
@field_validator("whisper_device")
@classmethod
def validate_whisper_device(cls, v: str) -> str:
diff --git a/src/free_claude_code/core/trace.py b/src/free_claude_code/core/trace.py
index 713e6337..88606b47 100644
--- a/src/free_claude_code/core/trace.py
+++ b/src/free_claude_code/core/trace.py
@@ -1,8 +1,9 @@
-"""Structured TRACE events for end-to-end request / CLI / provider logging.
+"""Structured DEBUG traces for end-to-end request / CLI / provider logging.
Emitted lines are merged into JSON log rows by ``config.logging_config``.
Conversation and Claude Code prompts are logged verbatim unless values live under
-sanitized credential keys (e.g. ``api_key``, ``authorization``).
+sanitized credential keys (e.g. ``api_key``, ``authorization``). The default
+INFO log level excludes these detailed request traces.
"""
import asyncio
@@ -49,7 +50,7 @@ def sanitize_trace_value(obj: Any) -> Any:
def trace_event(*, stage: str, event: str, source: str, **fields: Any) -> None:
- """Emit one structured TRACE row (merged into JSON by the log sink)."""
+ """Emit one structured DEBUG trace row merged into JSON by the log sink."""
payload = sanitize_trace_value(
{
"stage": stage,
@@ -58,7 +59,7 @@ def trace_event(*, stage: str, event: str, source: str, **fields: Any) -> None:
**fields,
},
)
- logger.bind(trace_payload=payload).info("TRACE {}", event)
+ logger.bind(trace_payload=payload).debug("TRACE {}", event)
async def close_stream_input(
diff --git a/src/free_claude_code/runtime/bootstrap.py b/src/free_claude_code/runtime/bootstrap.py
index e13c255e..55992bc5 100644
--- a/src/free_claude_code/runtime/bootstrap.py
+++ b/src/free_claude_code/runtime/bootstrap.py
@@ -23,7 +23,11 @@ def build_asgi_app(
) -> RuntimeASGIApp:
"""Construct the complete server application and its resource owner."""
log_path = Path(os.getenv("LOG_FILE", server_log_path()))
- configure_logging(log_path, verbose_third_party=settings.log_raw_api_payloads)
+ configure_logging(
+ log_path,
+ level=settings.log_level,
+ verbose_third_party=settings.log_raw_api_payloads,
+ )
provider_manager = ProviderRuntimeManager(settings)
runtime = ApplicationRuntime(
provider_manager,
diff --git a/tests/api/test_app_lifespan_and_errors.py b/tests/api/test_app_lifespan_and_errors.py
index 6a2e6daf..dcf79364 100644
--- a/tests/api/test_app_lifespan_and_errors.py
+++ b/tests/api/test_app_lifespan_and_errors.py
@@ -308,6 +308,7 @@ def test_bootstrap_configures_default_log_and_publishes_only_services(tmp_path):
configure.assert_called_once_with(
Path(log_path),
+ level=settings.log_level,
verbose_third_party=settings.log_raw_api_payloads,
)
api_app = cast(FastAPI, asgi_app.app)
diff --git a/tests/config/test_config.py b/tests/config/test_config.py
index 7f947e38..d02f9a4c 100644
--- a/tests/config/test_config.py
+++ b/tests/config/test_config.py
@@ -55,6 +55,7 @@ class TestSettings:
assert settings.log_raw_sse_events is False
assert settings.debug_platform_edits is False
assert settings.debug_subagent_stack is False
+ assert settings.log_level == "INFO"
assert settings.open_admin_browser is True
def test_open_admin_browser_loads_from_environment(self, monkeypatch):
diff --git a/tests/config/test_logging_config.py b/tests/config/test_logging_config.py
index 5bdc0ee7..66ed40b6 100644
--- a/tests/config/test_logging_config.py
+++ b/tests/config/test_logging_config.py
@@ -3,9 +3,11 @@
import json
import logging
from pathlib import Path
+from unittest.mock import patch
from loguru import logger
+from free_claude_code.config import logging_config
from free_claude_code.config.logging_config import configure_logging
@@ -50,22 +52,25 @@ def test_configure_logging_idempotent(tmp_path):
logger.info("After second configure")
-def test_configure_logging_skips_when_already_configured(tmp_path):
- """Without force, second call is a no-op (avoids reconfig on hot reload)."""
- log_file = str(tmp_path / "test.log")
- configure_logging(log_file, force=True)
- # Second call without force - should skip; no exception, log file unchanged
- configure_logging(str(tmp_path / "other.log"), force=False)
- # Logs still go to first file
- logger = logging.getLogger("test.skip")
- logger.info("Still goes to first file")
+def test_configure_logging_replaces_sink_when_path_changes(tmp_path):
+ """A path-only restart switches destinations without truncating either file."""
+ first_log = tmp_path / "first.log"
+ second_log = tmp_path / "nested" / "second.log"
+ configure_logging(first_log, force=True)
+
+ logger.info("first destination")
from loguru import logger as loguru_logger
loguru_logger.complete()
- assert (tmp_path / "test.log").exists()
- assert "Still goes to first file" in (tmp_path / "test.log").read_text(
- encoding="utf-8"
- )
+ configure_logging(second_log)
+ logger.info("second destination")
+ loguru_logger.complete()
+
+ first_text = first_log.read_text(encoding="utf-8")
+ second_text = second_log.read_text(encoding="utf-8")
+ assert "first destination" in first_text
+ assert "second destination" not in first_text
+ assert "second destination" in second_text
def test_telegram_bot_token_redacted_in_message_field(tmp_path) -> None:
@@ -101,3 +106,106 @@ def test_httpx_resets_to_notset_when_verbose_third_party(tmp_path) -> None:
log_file = str(tmp_path / "verbose.log")
configure_logging(log_file, force=True, verbose_third_party=True)
assert logging.getLogger("httpx").level == logging.NOTSET
+
+
+def test_configure_logging_respects_level(tmp_path) -> None:
+ """INFO level suppresses DEBUG messages from the file sink."""
+ log_file = str(tmp_path / "level.log")
+ configure_logging(log_file, force=True, level="INFO")
+
+ logger.debug("should not appear")
+ logger.info("should appear")
+ logger.complete()
+
+ text = Path(log_file).read_text(encoding="utf-8")
+ assert "should appear" in text
+ assert "should not appear" not in text
+
+
+def test_configure_logging_defaults_to_info(tmp_path) -> None:
+ """Customer default keeps lifecycle logs while suppressing debug diagnostics."""
+ log_file = str(tmp_path / "default.log")
+ configure_logging(log_file, force=True)
+
+ logger.debug("debug message")
+ logger.info("info message")
+ logger.complete()
+
+ text = Path(log_file).read_text(encoding="utf-8")
+ assert "debug message" not in text
+ assert "info message" in text
+
+
+def test_file_sink_bounds_rotated_log_retention(tmp_path) -> None:
+ """Five archives plus the active 50 MB file bound normal disk usage."""
+ log_file = tmp_path / "bounded.log"
+
+ with patch.object(logging_config.logger, "add", return_value=1) as add:
+ logging_config._add_file_sink(log_file, "INFO")
+
+ assert add.call_args.kwargs["rotation"] == "50 MB"
+ assert add.call_args.kwargs["retention"] == 5
+
+
+def test_configure_logging_handles_level_change_on_restart(tmp_path) -> None:
+ """Restart with a different level replaces the sink without truncating."""
+ log_file = str(tmp_path / "restart.log")
+
+ # First call: DEBUG level
+ configure_logging(log_file, force=True, level="DEBUG")
+ logger.debug("first debug")
+ logger.complete()
+
+ # Second call: change to INFO (simulates supervised restart)
+ configure_logging(log_file, level="INFO")
+ logger.debug("second debug")
+ logger.info("second info")
+ logger.complete()
+
+ text = Path(log_file).read_text(encoding="utf-8")
+ # First DEBUG message was written before the level change
+ assert "first debug" in text
+ # Second DEBUG is suppressed by the new INFO level
+ assert "second debug" not in text
+ # INFO messages appear regardless
+ assert "second info" in text
+
+
+def test_configure_logging_skips_when_level_unchanged(tmp_path) -> None:
+ """When level hasn't changed, the existing sink is reused."""
+ log_file = str(tmp_path / "same.log")
+ configure_logging(log_file, force=True, level="WARNING")
+ logger.warning("first warning")
+ logger.complete()
+
+ # Second call with same level — should be a no-op for the sink
+ configure_logging(log_file, level="WARNING")
+ logger.warning("second warning")
+ logger.complete()
+
+ text = Path(log_file).read_text(encoding="utf-8")
+ assert "first warning" in text
+ assert "second warning" in text
+
+
+def test_configure_logging_updates_verbosity_on_same_level(tmp_path) -> None:
+ """When verbose_third_party changes but level stays the same, third-party
+ logger levels are updated without touching the file sink."""
+ log_file = str(tmp_path / "verbosity.log")
+
+ # Start with verbosity off (third-party loggers at WARNING)
+ configure_logging(log_file, force=True, level="DEBUG", verbose_third_party=False)
+ assert logging.getLogger("httpx").level >= logging.WARNING
+ assert logging.getLogger("httpcore").level >= logging.WARNING
+ assert logging.getLogger("telegram").level >= logging.WARNING
+
+ # Restart with same level but verbosity on
+ configure_logging(log_file, level="DEBUG", verbose_third_party=True)
+ assert logging.getLogger("httpx").level == logging.NOTSET
+ assert logging.getLogger("httpcore").level == logging.NOTSET
+ assert logging.getLogger("telegram").level == logging.NOTSET
+
+ # Log file sink still works
+ logger.info("still logging")
+ logger.complete()
+ assert "still logging" in Path(log_file).read_text(encoding="utf-8")
diff --git a/tests/core/test_trace.py b/tests/core/test_trace.py
index 60c0614f..528e14d7 100644
--- a/tests/core/test_trace.py
+++ b/tests/core/test_trace.py
@@ -56,9 +56,10 @@ def _json_log_rows(log_file: str) -> list[dict]:
def test_trace_payload_merged_into_json_line(tmp_path) -> None:
log_file = str(tmp_path / "t.log")
- configure_logging(log_file, force=True)
+ configure_logging(log_file, force=True, level="DEBUG")
trace_event(stage="s", event="e.v1", source="unit", hello="world", n=42)
row = _json_log_rows(log_file)[-1]
+ assert row["level"] == "DEBUG"
assert row["trace"] is True
assert row["stage"] == "s"
assert row["event"] == "e.v1"
@@ -68,6 +69,17 @@ def test_trace_payload_merged_into_json_line(tmp_path) -> None:
assert TRACE_PAYLOAD_BINDING == "trace_payload"
+def test_trace_payload_excluded_from_default_info_logs(tmp_path) -> None:
+ log_file = str(tmp_path / "default.log")
+ configure_logging(log_file, force=True)
+
+ trace_event(stage="s", event="hidden", source="unit")
+ logger.info("visible lifecycle event")
+
+ rows = _json_log_rows(log_file)
+ assert [row["message"] for row in rows] == ["visible lifecycle event"]
+
+
def test_sanitize_masks_nested_api_key_strings() -> None:
"""Credential-shaped keys redact without touching normal message text."""
from free_claude_code.core.trace import sanitize_trace_value
@@ -82,7 +94,7 @@ def test_sanitize_masks_nested_api_key_strings() -> None:
@pytest.mark.asyncio
async def test_traced_async_stream_logs_completion(tmp_path) -> None:
log_file = str(tmp_path / "complete.log")
- configure_logging(log_file, force=True)
+ configure_logging(log_file, force=True, level="DEBUG")
source = _CloseTrackingIterator(["hello", " world"])
@@ -111,7 +123,7 @@ async def test_traced_async_stream_logs_completion(tmp_path) -> None:
@pytest.mark.asyncio
async def test_traced_async_stream_logs_real_exception(tmp_path) -> None:
log_file = str(tmp_path / "error.log")
- configure_logging(log_file, force=True)
+ configure_logging(log_file, force=True, level="DEBUG")
source = _CloseTrackingIterator(
["before"],
@@ -151,7 +163,7 @@ async def test_traced_async_stream_logs_real_exception(tmp_path) -> None:
@pytest.mark.asyncio
async def test_traced_async_stream_closes_quietly_on_generator_exit(tmp_path) -> None:
log_file = str(tmp_path / "generator_exit.log")
- configure_logging(log_file, force=True)
+ configure_logging(log_file, force=True, level="DEBUG")
source = _CloseTrackingIterator(["first", "second"])
diff --git a/uv.lock b/uv.lock
index 15875ee1..c4c19516 100644
--- a/uv.lock
+++ b/uv.lock
@@ -561,7 +561,7 @@ wheels = [
[[package]]
name = "free-claude-code"
-version = "4.7.2"
+version = "4.7.3"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },