Skip to content

Commit 3fb1fe2

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

7 files changed

Lines changed: 107 additions & 23 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: dict[str, Any] = {}
279+
if should_use_rich_logs():
280+
extra_uvicorn_kwargs["log_config"] = get_uvicorn_log_config()
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/logging.py

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,38 @@
11
import logging
22

3-
from rich.console import Console
3+
from rich.errors import MarkupError
44
from rich.logging import RichHandler
5+
from rich.markup import render
56

7+
from .utils.cli import should_use_rich_logs
68

7-
def setup_logging(terminal_width: int | None = None, level: int = logging.INFO) -> None:
9+
10+
class PlainFormatter(logging.Formatter):
11+
def formatMessage(self, record: logging.LogRecord) -> str:
12+
try:
13+
record.message = render(record.message, emoji=False).plain
14+
except MarkupError:
15+
pass
16+
return super().formatMessage(record)
17+
18+
19+
def setup_logging(level: int = logging.INFO) -> None:
820
logger = logging.getLogger("fastapi_cli")
9-
console = Console(width=terminal_width) if terminal_width else None
10-
rich_handler = RichHandler(
11-
show_time=False,
12-
rich_tracebacks=True,
13-
tracebacks_show_locals=True,
14-
markup=True,
15-
show_path=False,
16-
console=console,
17-
)
18-
rich_handler.setFormatter(logging.Formatter("%(message)s"))
19-
logger.addHandler(rich_handler)
21+
if should_use_rich_logs():
22+
rich_handler = RichHandler(
23+
show_time=False,
24+
rich_tracebacks=True,
25+
tracebacks_show_locals=True,
26+
markup=True,
27+
show_path=False,
28+
)
29+
rich_handler.setFormatter(logging.Formatter("%(message)s"))
30+
handler: logging.Handler = rich_handler
31+
else:
32+
handler = logging.StreamHandler()
33+
handler.setFormatter(PlainFormatter("%(levelname)s:%(name)s:%(message)s"))
34+
35+
logger.addHandler(handler)
2036

2137
logger.setLevel(level)
2238
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/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: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
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.logging import PlainFormatter
9+
from fastapi_cli.utils.cli import (
10+
CustomFormatter,
11+
get_uvicorn_log_config,
12+
should_use_rich_logs,
13+
)
714

815

916
def test_get_uvicorn_config_uses_custom_formatter() -> None:
@@ -14,6 +21,32 @@ def test_get_uvicorn_config_uses_custom_formatter() -> None:
1421
assert config["loggers"]["uvicorn"]["propagate"] is False
1522

1623

24+
def test_should_use_rich_logs_is_false_without_tty(
25+
monkeypatch: MonkeyPatch,
26+
) -> None:
27+
monkeypatch.setattr(sys, "stdout", io.StringIO())
28+
29+
assert should_use_rich_logs() is False
30+
31+
32+
def test_plain_formatter_strips_rich_markup() -> None:
33+
formatter = PlainFormatter("%(levelname)s:%(name)s:%(message)s")
34+
record = logging.LogRecord(
35+
name="fastapi_cli.discover",
36+
level=logging.WARNING,
37+
pathname="",
38+
lineno=0,
39+
msg="Ensure all the package directories have an [blue]__init__.py[/blue] file",
40+
args=(),
41+
exc_info=None,
42+
)
43+
44+
assert (
45+
formatter.format(record)
46+
== "WARNING:fastapi_cli.discover:Ensure all the package directories have an __init__.py file"
47+
)
48+
49+
1750
def test_custom_formatter() -> None:
1851
formatter = CustomFormatter()
1952

tests/test_utils_package.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from pathlib import Path
22

33
import pytest
4-
from pytest import CaptureFixture
4+
from pytest import LogCaptureFixture
55

66
from fastapi_cli.discover import get_import_data
77
from fastapi_cli.exceptions import FastAPICLIException
@@ -158,15 +158,17 @@ def test_package_dir_explicit_app() -> None:
158158
assert import_data.module_data.module_import_str == "package"
159159

160160

161-
def test_broken_package_dir(capsys: CaptureFixture[str]) -> None:
161+
def test_broken_package_dir(caplog: LogCaptureFixture) -> None:
162162
with changing_dir(assets_path):
163163
# TODO (when deprecating Python 3.8): remove ValueError
164164
with pytest.raises((ImportError, ValueError)):
165165
get_import_data(path=Path("broken_package/mod/app.py"))
166166

167-
captured = capsys.readouterr()
168-
assert "Import error:" in captured.out
169-
assert "Ensure all the package directories have an __init__.py file" in captured.out
167+
assert "Import error:" in caplog.text
168+
assert (
169+
"Ensure all the package directories have an [blue]__init__.py[/blue] file"
170+
in caplog.text
171+
)
170172

171173

172174
def test_package_dir_no_app() -> None:

0 commit comments

Comments
 (0)