|
| 1 | +import logging |
| 2 | +import re |
| 3 | +from datetime import datetime |
| 4 | +from pathlib import Path |
| 5 | +from typing import Annotated, Optional |
| 6 | + |
| 7 | +import typer |
| 8 | +from rich.markup import escape |
| 9 | +from rich_toolkit import RichToolkit |
| 10 | + |
| 11 | +from fastapi_cloud_cli.utils.api import ( |
| 12 | + APIClient, |
| 13 | + AppLogEntry, |
| 14 | + StreamLogError, |
| 15 | + TooManyRetriesError, |
| 16 | +) |
| 17 | +from fastapi_cloud_cli.utils.apps import AppConfig, get_app_config |
| 18 | +from fastapi_cloud_cli.utils.auth import Identity |
| 19 | +from fastapi_cloud_cli.utils.cli import get_rich_toolkit |
| 20 | + |
| 21 | +logger = logging.getLogger(__name__) |
| 22 | + |
| 23 | + |
| 24 | +LOG_LEVEL_COLORS = { |
| 25 | + "debug": "blue", |
| 26 | + "info": "cyan", |
| 27 | + "warning": "yellow", |
| 28 | + "warn": "yellow", |
| 29 | + "error": "red", |
| 30 | + "critical": "magenta", |
| 31 | + "fatal": "magenta", |
| 32 | +} |
| 33 | + |
| 34 | +SINCE_PATTERN = re.compile(r"^\d+[smhd]$") |
| 35 | + |
| 36 | + |
| 37 | +def _validate_since(value: str) -> str: |
| 38 | + """Validate the --since parameter format.""" |
| 39 | + if not SINCE_PATTERN.match(value): |
| 40 | + raise typer.BadParameter( |
| 41 | + "Invalid format. Use a number followed by s, m, h, or d (e.g., '5m', '1h', '2d')." |
| 42 | + ) |
| 43 | + |
| 44 | + return value |
| 45 | + |
| 46 | + |
| 47 | +def _format_log_line(log: AppLogEntry) -> str: |
| 48 | + """Format a log entry for display with a colored indicator""" |
| 49 | + # Parse the timestamp string to format it consistently |
| 50 | + timestamp = datetime.fromisoformat(log.timestamp.replace("Z", "+00:00")) |
| 51 | + timestamp_str = timestamp.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" |
| 52 | + color = LOG_LEVEL_COLORS.get(log.level.lower()) |
| 53 | + |
| 54 | + message = escape(log.message) |
| 55 | + |
| 56 | + if color: |
| 57 | + return f"[{color}]┃[/{color}] [dim]{timestamp_str}[/dim] {message}" |
| 58 | + |
| 59 | + return f"[dim]┃[/dim] [dim]{timestamp_str}[/dim] {message}" |
| 60 | + |
| 61 | + |
| 62 | +def _process_log_stream( |
| 63 | + toolkit: RichToolkit, |
| 64 | + app_config: AppConfig, |
| 65 | + tail: int, |
| 66 | + since: str, |
| 67 | + follow: bool, |
| 68 | +) -> None: |
| 69 | + """Stream app logs and print them to the console.""" |
| 70 | + log_count = 0 |
| 71 | + |
| 72 | + try: |
| 73 | + with APIClient() as client: |
| 74 | + for log in client.stream_app_logs( |
| 75 | + app_id=app_config.app_id, |
| 76 | + tail=tail, |
| 77 | + since=since, |
| 78 | + follow=follow, |
| 79 | + ): |
| 80 | + toolkit.print(_format_log_line(log)) |
| 81 | + log_count += 1 |
| 82 | + |
| 83 | + if not follow and log_count == 0: |
| 84 | + toolkit.print("No logs found for the specified time range.") |
| 85 | + return |
| 86 | + except KeyboardInterrupt: # pragma: no cover |
| 87 | + toolkit.print_line() |
| 88 | + return |
| 89 | + except StreamLogError as e: |
| 90 | + error_msg = str(e) |
| 91 | + if "HTTP 401" in error_msg or "HTTP 403" in error_msg: |
| 92 | + toolkit.print( |
| 93 | + "The specified token is not valid. Use [blue]`fastapi login`[/] to generate a new token.", |
| 94 | + ) |
| 95 | + elif "HTTP 404" in error_msg: |
| 96 | + toolkit.print( |
| 97 | + "App not found. Make sure to use the correct account.", |
| 98 | + ) |
| 99 | + else: |
| 100 | + toolkit.print( |
| 101 | + f"[red]Error:[/] {escape(error_msg)}", |
| 102 | + ) |
| 103 | + raise typer.Exit(1) from None |
| 104 | + except (TooManyRetriesError, TimeoutError): |
| 105 | + toolkit.print( |
| 106 | + "Lost connection to log stream. Please try again later.", |
| 107 | + ) |
| 108 | + raise typer.Exit(1) from None |
| 109 | + |
| 110 | + |
| 111 | +def logs( |
| 112 | + path: Annotated[ |
| 113 | + Optional[Path], |
| 114 | + typer.Argument( |
| 115 | + help="Path to the folder containing the app (defaults to current directory)" |
| 116 | + ), |
| 117 | + ] = None, |
| 118 | + tail: int = typer.Option( |
| 119 | + 100, |
| 120 | + "--tail", |
| 121 | + "-t", |
| 122 | + help="Number of log lines to show before streaming.", |
| 123 | + show_default=True, |
| 124 | + ), |
| 125 | + since: str = typer.Option( |
| 126 | + "5m", |
| 127 | + "--since", |
| 128 | + "-s", |
| 129 | + help="Show logs since a specific time (e.g., '5m', '1h', '2d').", |
| 130 | + show_default=True, |
| 131 | + callback=_validate_since, |
| 132 | + ), |
| 133 | + follow: bool = typer.Option( |
| 134 | + True, |
| 135 | + "--follow/--no-follow", |
| 136 | + "-f", |
| 137 | + help="Stream logs in real-time (use --no-follow to fetch and exit).", |
| 138 | + ), |
| 139 | +) -> None: |
| 140 | + """Stream or fetch logs from your deployed app. |
| 141 | +
|
| 142 | + Examples: |
| 143 | + fastapi cloud logs # Stream logs in real-time |
| 144 | + fastapi cloud logs --no-follow # Fetch recent logs and exit |
| 145 | + fastapi cloud logs --tail 50 --since 1h # Last 50 logs from the past hour |
| 146 | + """ |
| 147 | + identity = Identity() |
| 148 | + with get_rich_toolkit(minimal=True) as toolkit: |
| 149 | + if not identity.is_logged_in(): |
| 150 | + toolkit.print( |
| 151 | + "No credentials found. Use [blue]`fastapi login`[/] to login.", |
| 152 | + tag="auth", |
| 153 | + ) |
| 154 | + raise typer.Exit(1) |
| 155 | + |
| 156 | + app_path = path or Path.cwd() |
| 157 | + app_config = get_app_config(app_path) |
| 158 | + |
| 159 | + if not app_config: |
| 160 | + toolkit.print( |
| 161 | + "No app linked to this directory. Run [blue]`fastapi deploy`[/] first.", |
| 162 | + ) |
| 163 | + raise typer.Exit(1) |
| 164 | + |
| 165 | + logger.debug("Fetching logs for app ID: %s", app_config.app_id) |
| 166 | + |
| 167 | + if follow: |
| 168 | + toolkit.print( |
| 169 | + f"Streaming logs for [bold]{app_config.app_id}[/bold] (Ctrl+C to exit)...", |
| 170 | + tag="logs", |
| 171 | + ) |
| 172 | + else: |
| 173 | + toolkit.print( |
| 174 | + f"Fetching logs for [bold]{app_config.app_id}[/bold]...", |
| 175 | + tag="logs", |
| 176 | + ) |
| 177 | + toolkit.print_line() |
| 178 | + |
| 179 | + _process_log_stream( |
| 180 | + toolkit=toolkit, |
| 181 | + app_config=app_config, |
| 182 | + tail=tail, |
| 183 | + since=since, |
| 184 | + follow=follow, |
| 185 | + ) |
0 commit comments