|
| 1 | +"""Core print logic.""" |
| 2 | + |
| 3 | +import json |
| 4 | +from copy import copy |
| 5 | +from typing import Any |
| 6 | + |
| 7 | +from beartype import beartype |
| 8 | +from loguru import logger |
| 9 | +from pydantic import BaseModel |
| 10 | +from rich.console import Console |
| 11 | +from rich.text import Text |
| 12 | + |
| 13 | +from .config import Config |
| 14 | + |
| 15 | + |
| 16 | +@beartype |
| 17 | +def pop_key(data: dict, keys: list[str], fallback: str) -> Any: |
| 18 | + """Recursively pop whichever key matches first or default to the fallback.""" |
| 19 | + try: |
| 20 | + key = keys.pop(0) |
| 21 | + return data.pop(key, None) or pop_key(data, keys, fallback) |
| 22 | + except IndexError: |
| 23 | + return fallback |
| 24 | + |
| 25 | + |
| 26 | +class Record(BaseModel): |
| 27 | + """Record Model.""" |
| 28 | + |
| 29 | + timestamp: str |
| 30 | + level: str |
| 31 | + message: str |
| 32 | + data: dict |
| 33 | + |
| 34 | + @classmethod |
| 35 | + def from_line(cls, data: dict, config: Config) -> 'Record': |
| 36 | + """Extract Record from jsonl.""" |
| 37 | + return cls( |
| 38 | + timestamp=pop_key(data, copy(config.keys.timestamp), '<no timestamp>'), |
| 39 | + level=pop_key(data, copy(config.keys.level), '<no level>'), |
| 40 | + message=pop_key(data, copy(config.keys.message), '<no message>'), |
| 41 | + data=data, |
| 42 | + ) |
| 43 | + |
| 44 | + |
| 45 | +@beartype |
| 46 | +def print_record(line: str, console: Console, config: Config) -> None: |
| 47 | + """Format and print the record.""" |
| 48 | + try: |
| 49 | + record = Record.from_line(json.loads(line), config=config) |
| 50 | + except Exception: |
| 51 | + logger.exception('Error in tail-json to parse line', line=line) |
| 52 | + console.print('') # Line break |
| 53 | + return |
| 54 | + |
| 55 | + text = Text(tab_size=4) # FIXME: Why isn't this indenting what is wrapped? |
| 56 | + text.append(f'{record.timestamp: <28}', style=config.styles.timestamp) |
| 57 | + text.append(f' {record.level: <7}', style=config.styles.get_level_style(record.level)) |
| 58 | + text.append(f' {record.message: <20}', style=config.styles.message) |
| 59 | + |
| 60 | + full_lines = [] |
| 61 | + for key in config.keys.on_own_line: |
| 62 | + line = record.data.pop(key, None) |
| 63 | + if line: |
| 64 | + full_lines.append((key, line)) |
| 65 | + |
| 66 | + for key, value in record.data.items(): |
| 67 | + text.append(f' {key}:', style=config.styles.key) |
| 68 | + text.append(f' {str(value): <10}', style=config.styles.value) |
| 69 | + |
| 70 | + console.print(text) |
| 71 | + for key, line in full_lines: |
| 72 | + new_text = Text() |
| 73 | + new_text.append(f' ∟ {key}', style='bold green') |
| 74 | + new_text.append(f': {line}') |
| 75 | + console.print(new_text) |
0 commit comments