Skip to content

Commit 0ce6ca6

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

6 files changed

Lines changed: 87 additions & 9 deletions

File tree

src/fastapi_cli/cli.py

Lines changed: 12 additions & 3 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"]}
@@ -99,7 +103,8 @@ def callback(
99103

100104
log_level = logging.DEBUG if verbose else logging.INFO
101105

102-
setup_logging(level=log_level)
106+
if should_use_rich_logs():
107+
setup_logging(level=log_level)
103108

104109

105110
def _get_module_tree(module_paths: list[Path]) -> Tree:
@@ -271,6 +276,10 @@ def _run(
271276
toolkit.print("Logs:")
272277
toolkit.print_line()
273278

279+
extra_uvicorn_kwargs: dict[str, Any] = {}
280+
if should_use_rich_logs():
281+
extra_uvicorn_kwargs["log_config"] = get_uvicorn_log_config()
282+
274283
uvicorn.run(
275284
app=import_string,
276285
host=host,
@@ -285,7 +294,7 @@ def _run(
285294
root_path=root_path,
286295
proxy_headers=proxy_headers,
287296
forwarded_allow_ips=forwarded_allow_ips,
288-
log_config=get_uvicorn_log_config(),
297+
**extra_uvicorn_kwargs,
289298
)
290299

291300

src/fastapi_cli/logging.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,23 @@
44
from rich.logging import RichHandler
55

66

7-
def setup_logging(terminal_width: int | None = None, level: int = logging.INFO) -> None:
7+
def setup_logging(
8+
terminal_width: int | None = None,
9+
level: int = logging.INFO,
10+
) -> None:
811
logger = logging.getLogger("fastapi_cli")
912
console = Console(width=terminal_width) if terminal_width else None
10-
rich_handler = RichHandler(
13+
handler: logging.Handler = RichHandler(
1114
show_time=False,
1215
rich_tracebacks=True,
1316
tracebacks_show_locals=True,
1417
markup=True,
1518
show_path=False,
1619
console=console,
1720
)
18-
rich_handler.setFormatter(logging.Formatter("%(message)s"))
19-
logger.addHandler(rich_handler)
21+
handler.setFormatter(logging.Formatter("%(message)s"))
22+
23+
logger.addHandler(handler)
2024

2125
logger.setLevel(level)
2226
logger.propagate = False

src/fastapi_cli/utils/cli.py

Lines changed: 5 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,10 @@ def formatMessage(self, record: logging.LogRecord) -> str:
2021
return result
2122

2223

24+
def should_use_rich_logs() -> bool:
25+
return sys.stdout.isatty()
26+
27+
2328
def get_uvicorn_log_config() -> dict[str, Any]:
2429
return {
2530
"version": 1,

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_logging.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import logging
2+
3+
from rich.logging import RichHandler
4+
5+
from fastapi_cli.logging import setup_logging
6+
7+
8+
def test_setup_logging_uses_rich_handler() -> None:
9+
logger = logging.getLogger("fastapi_cli")
10+
original_handlers = logger.handlers[:]
11+
original_level = logger.level
12+
original_propagate = logger.propagate
13+
try:
14+
logger.handlers = []
15+
16+
setup_logging()
17+
18+
assert len(logger.handlers) == 1
19+
assert isinstance(logger.handlers[0], RichHandler)
20+
finally:
21+
for handler in logger.handlers:
22+
if handler not in original_handlers:
23+
handler.close()
24+
logger.handlers = original_handlers
25+
logger.setLevel(original_level)
26+
logger.propagate = original_propagate

tests/test_utils_cli.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
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
57

6-
from fastapi_cli.utils.cli import CustomFormatter, get_uvicorn_log_config
8+
from fastapi_cli.utils.cli import (
9+
CustomFormatter,
10+
get_uvicorn_log_config,
11+
should_use_rich_logs,
12+
)
713

814

915
def test_get_uvicorn_config_uses_custom_formatter() -> None:
@@ -14,6 +20,14 @@ def test_get_uvicorn_config_uses_custom_formatter() -> None:
1420
assert config["loggers"]["uvicorn"]["propagate"] is False
1521

1622

23+
def test_should_use_rich_logs_is_false_without_tty(
24+
monkeypatch: MonkeyPatch,
25+
) -> None:
26+
monkeypatch.setattr(sys, "stdout", io.StringIO())
27+
28+
assert should_use_rich_logs() is False
29+
30+
1731
def test_custom_formatter() -> None:
1832
formatter = CustomFormatter()
1933

0 commit comments

Comments
 (0)