Skip to content

feat: make rich logger optional #182

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
29 changes: 17 additions & 12 deletions src/fastapi_cli/logging.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
import sys
from typing import Union

from rich.console import Console
Expand All @@ -9,17 +10,21 @@ def setup_logging(
terminal_width: Union[int, None] = None, level: int = logging.INFO
) -> None:
logger = logging.getLogger("fastapi_cli")
console = Console(width=terminal_width) if terminal_width else None
rich_handler = RichHandler(
show_time=False,
rich_tracebacks=True,
tracebacks_show_locals=True,
markup=True,
show_path=False,
console=console,
)
rich_handler.setFormatter(logging.Formatter("%(message)s"))
logger.addHandler(rich_handler)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did you remove logger.addHandler(rich_handler)?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I removed rich handler because, as a part of https://github.com/Textualize/rich it makes assumptions about output being console. In no way does this compromise logging capabilities when output is redirected to file.

Logging handlers and formatters can be set by the outside code, e.g. the way you set logging config for uvicorn here: https://github.com/fastapi/fastapi-cli/blob/main/src/fastapi_cli/cli.py#L180

Here is how I set logging config via a single yaml

if sys.stdout.isatty():
# This is a real terminal, use ANSI escape sequences for colored output
console = Console(width=terminal_width) if terminal_width else None
rich_handler = RichHandler(
show_time=False,
rich_tracebacks=True,
tracebacks_show_locals=True,
markup=True,
show_path=False,
console=console,
)
rich_handler.setFormatter(logging.Formatter("%(message)s"))
logger.propagate = False
else:
# You're being piped or redirected - pass it to the root logger
pass

logger.setLevel(level)
logger.propagate = False
Loading