Skip to content

Commit 71426ad

Browse files
committed
🐛 Avoid fancy logs for non-TTY output
Shortcake-Parent: main
1 parent daeba73 commit 71426ad

5 files changed

Lines changed: 73 additions & 5 deletions

File tree

src/fastapi_cli/cli.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,11 @@
2020

2121
from . import __version__
2222
from .logging import setup_logging
23-
from .utils.cli import get_rich_toolkit, get_uvicorn_log_config
23+
from .utils.cli import (
24+
get_rich_toolkit,
25+
get_uvicorn_log_config,
26+
should_use_rich_logs,
27+
)
2428

2529
app = typer.Typer(
2630
rich_markup_mode="rich", context_settings={"help_option_names": ["-h", "--help"]}
@@ -271,6 +275,10 @@ def _run(
271275
toolkit.print("Logs:")
272276
toolkit.print_line()
273277

278+
extra_uvicorn_kwargs = (
279+
get_uvicorn_log_config() if should_use_rich_logs() else {}
280+
)
281+
274282
uvicorn.run(
275283
app=import_string,
276284
host=host,
@@ -285,7 +293,7 @@ def _run(
285293
root_path=root_path,
286294
proxy_headers=proxy_headers,
287295
forwarded_allow_ips=forwarded_allow_ips,
288-
log_config=get_uvicorn_log_config(),
296+
**extra_uvicorn_kwargs,
289297
)
290298

291299

src/fastapi_cli/utils/cli.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import logging
2+
import sys
23
from typing import Any
34

45
from rich_toolkit import RichToolkit, RichToolkitTheme
@@ -20,6 +21,11 @@ def formatMessage(self, record: logging.LogRecord) -> str:
2021
return result
2122

2223

24+
def should_use_rich_logs() -> bool:
25+
"""Return True when stdout is a TTY and rich logs should be used, False otherwise."""
26+
return sys.stdout.isatty()
27+
28+
2329
def get_uvicorn_log_config() -> dict[str, Any]:
2430
return {
2531
"version": 1,

tests/conftest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,5 @@ def reset_syspath() -> Generator[None, None, None]:
2020
def setup_terminal() -> None:
2121
rich_utils.MAX_WIDTH = 3000
2222
rich_utils.FORCE_TERMINAL = False
23-
setup_logging(terminal_width=3000)
23+
setup_logging()
2424
return

tests/test_cli.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@
1616
assets_path = Path(__file__).parent / "assets"
1717

1818

19+
@pytest.fixture(autouse=True)
20+
def force_rich_logs(monkeypatch: pytest.MonkeyPatch) -> None:
21+
monkeypatch.setattr("fastapi_cli.cli.should_use_rich_logs", lambda: True)
22+
23+
1924
def test_dev() -> None:
2025
with changing_dir(assets_path):
2126
with patch.object(uvicorn, "run") as mock_run:
@@ -51,6 +56,21 @@ def test_dev() -> None:
5156
assert "🐍 single_file_app.py" in result.output
5257

5358

59+
def test_run_uses_uvicorn_default_log_config_without_rich_logs(
60+
monkeypatch: pytest.MonkeyPatch,
61+
) -> None:
62+
monkeypatch.setattr("fastapi_cli.cli.should_use_rich_logs", lambda: False)
63+
64+
with changing_dir(assets_path):
65+
with patch.object(uvicorn, "run") as mock_run:
66+
result = runner.invoke(app, ["run", "single_file_app.py"])
67+
assert result.exit_code == 0, result.output
68+
assert mock_run.called
69+
assert mock_run.call_args
70+
71+
assert "log_config" not in mock_run.call_args.kwargs
72+
73+
5474
def test_dev_no_args_auto_discovery() -> None:
5575
"""Test that auto-discovery works when no args and no pyproject.toml entrypoint"""
5676
with changing_dir(assets_path / "default_files" / "default_main"):

tests/test_utils_cli.py

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,17 @@
1+
import io
12
import logging
3+
import sys
24
from logging.config import dictConfig
35

4-
from pytest import LogCaptureFixture
6+
from pytest import LogCaptureFixture, MonkeyPatch
7+
from rich.logging import RichHandler
58

6-
from fastapi_cli.utils.cli import CustomFormatter, get_uvicorn_log_config
9+
from fastapi_cli import logging as cli_logging
10+
from fastapi_cli.utils.cli import (
11+
CustomFormatter,
12+
get_uvicorn_log_config,
13+
should_use_rich_logs,
14+
)
715

816

917
def test_get_uvicorn_config_uses_custom_formatter() -> None:
@@ -14,6 +22,32 @@ def test_get_uvicorn_config_uses_custom_formatter() -> None:
1422
assert config["loggers"]["uvicorn"]["propagate"] is False
1523

1624

25+
def test_should_use_rich_logs_is_false_without_tty(
26+
monkeypatch: MonkeyPatch,
27+
) -> None:
28+
monkeypatch.setattr(sys, "stdout", io.StringIO())
29+
30+
assert should_use_rich_logs() is False
31+
32+
33+
def test_setup_logging_uses_rich_handler() -> None:
34+
logger = logging.getLogger("fastapi_cli")
35+
original_handlers = logger.handlers.copy()
36+
original_level = logger.level
37+
original_propagate = logger.propagate
38+
logger.handlers.clear()
39+
try:
40+
cli_logging.setup_logging(level=logging.DEBUG)
41+
42+
assert isinstance(logger.handlers[0], RichHandler)
43+
assert logger.level == logging.DEBUG
44+
assert logger.propagate is False
45+
finally:
46+
logger.handlers = original_handlers
47+
logger.setLevel(original_level)
48+
logger.propagate = original_propagate
49+
50+
1751
def test_custom_formatter() -> None:
1852
formatter = CustomFormatter()
1953

0 commit comments

Comments
 (0)