File size: 5,601 Bytes
d2585c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
"""๊ตฌ์กฐํ™” ๋กœ๊ทธ ์‹œ์Šคํ…œ โ€” JSON Lines + Rich ํ„ฐ๋ฏธ๋„ ๋™์‹œ ์ถœ๋ ฅ.

๋กœ๊ทธ ๋ ˆ๋ฒจ:
  FLOW   โ€” ํŒŒ์ดํ”„๋ผ์ธ ๋…ธ๋“œ ์ „์ด (session_load -> planner -> ...)
  METRIC โ€” ๋ ˆ์ดํ„ด์‹œ, ํ† ํฐ ์ˆ˜, ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰
  ASSERT โ€” ์‹œ๋‚˜๋ฆฌ์˜ค ๊ฒ€์ฆ ๊ฒฐ๊ณผ (PASS/FAIL/WARN)
  DEBUG  โ€” HTTP ์š”์ฒญ/์‘๋‹ต ์ƒ์„ธ
"""

from __future__ import annotations

import json
import sys
import time
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional

try:
    from rich.console import Console
    from rich.live import Live
    from rich.table import Table
    from rich.text import Text

    RICH_AVAILABLE = True
except ImportError:
    RICH_AVAILABLE = False


@dataclass
class LogEntry:
    """๋‹จ์ผ ๋กœ๊ทธ ์—”ํŠธ๋ฆฌ."""

    timestamp: str
    level: str  # FLOW | METRIC | ASSERT | INFO | WARN | ERROR | DEBUG
    phase: int
    scenario_id: int
    message: str
    data: Dict[str, Any] = field(default_factory=dict)

    def to_json(self) -> str:
        return json.dumps(asdict(self), ensure_ascii=False)


class E2ELogger:
    """๋“€์–ผ ์ถœ๋ ฅ ๋กœ๊ฑฐ: JSON Lines ํŒŒ์ผ + ํ„ฐ๋ฏธ๋„."""

    def __init__(self, log_path: str, verbose: bool = True) -> None:
        self._log_path = Path(log_path)
        self._verbose = verbose
        self._entries: List[LogEntry] = []
        self._file = open(self._log_path, "w", encoding="utf-8")  # noqa: SIM115
        self._console = Console(stderr=True) if RICH_AVAILABLE else None
        self._phase = 0
        self._scenario_id = 0

    def set_context(self, phase: int = 0, scenario_id: int = 0) -> None:
        self._phase = phase
        self._scenario_id = scenario_id

    def _write(self, entry: LogEntry) -> None:
        self._entries.append(entry)
        line = entry.to_json()
        self._file.write(line + "\n")
        self._file.flush()

        if self._verbose:
            self._print_terminal(entry)

    def _print_terminal(self, entry: LogEntry) -> None:
        level = entry.level
        tag_map = {
            "FLOW": "[cyan][FLOW][/cyan]" if RICH_AVAILABLE else "[FLOW]",
            "METRIC": "[blue][METRIC][/blue]" if RICH_AVAILABLE else "[METRIC]",
            "ASSERT": "[green][ASSERT][/green]" if RICH_AVAILABLE else "[ASSERT]",
            "INFO": "[white][INFO][/white]" if RICH_AVAILABLE else "[INFO]",
            "WARN": "[yellow][WARN][/yellow]" if RICH_AVAILABLE else "[WARN]",
            "ERROR": "[red][ERROR][/red]" if RICH_AVAILABLE else "[ERROR]",
            "DEBUG": "[dim][DEBUG][/dim]" if RICH_AVAILABLE else "[DEBUG]",
        }
        tag = tag_map.get(level, f"[{level}]")

        if self._console and RICH_AVAILABLE:
            self._console.print(f"{entry.timestamp} {tag} {entry.message}")
        else:
            plain_tag = f"[{level}]"
            print(f"{entry.timestamp} {plain_tag} {entry.message}", file=sys.stderr)

    def _now(self) -> str:
        return time.strftime("%Y-%m-%d %H:%M:%S")

    def flow(self, message: str, **data: Any) -> None:
        self._write(LogEntry(self._now(), "FLOW", self._phase, self._scenario_id, message, data))

    def metric(self, message: str, **data: Any) -> None:
        self._write(LogEntry(self._now(), "METRIC", self._phase, self._scenario_id, message, data))

    def assertion(self, message: str, **data: Any) -> None:
        self._write(LogEntry(self._now(), "ASSERT", self._phase, self._scenario_id, message, data))

    def info(self, message: str, **data: Any) -> None:
        self._write(LogEntry(self._now(), "INFO", self._phase, self._scenario_id, message, data))

    def warn(self, message: str, **data: Any) -> None:
        self._write(LogEntry(self._now(), "WARN", self._phase, self._scenario_id, message, data))

    def error(self, message: str, **data: Any) -> None:
        self._write(LogEntry(self._now(), "ERROR", self._phase, self._scenario_id, message, data))

    def debug(self, message: str, **data: Any) -> None:
        if self._verbose:
            self._write(
                LogEntry(self._now(), "DEBUG", self._phase, self._scenario_id, message, data)
            )

    def scenario_result(
        self,
        scenario_id: int,
        name: str,
        phase: int,
        status: str,
        elapsed: float,
        attempts: int = 1,
        assertions: Optional[List[str]] = None,
        warnings: Optional[List[str]] = None,
        error: Optional[str] = None,
        detail: Optional[Any] = None,
    ) -> dict:
        """์‹œ๋‚˜๋ฆฌ์˜ค ๊ฒฐ๊ณผ๋ฅผ ๋กœ๊ทธ์— ๊ธฐ๋กํ•˜๊ณ  ๊ฒฐ๊ณผ dict๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค."""
        tag = {"passed": "PASS", "failed": "FAIL", "skipped": "SKIP"}.get(status, "????")

        msg = f"[{tag}] Scenario {scenario_id}: {name} ({elapsed:.2f}s)"
        if status == "passed":
            self.assertion(msg)
        elif status == "skipped":
            self.warn(f"{msg} -- {error or 'skipped'}")
        else:
            self.error(f"{msg} -- {error}")

        if warnings:
            for w in warnings:
                self.warn(f"  [WARN] {w}")

        entry = {
            "id": scenario_id,
            "name": name,
            "phase": phase,
            "status": status,
            "attempts": attempts,
            "elapsed_s": round(elapsed, 3),
            "assertions": assertions or [],
            "warnings": warnings or [],
            "error": error,
            "detail": detail,
        }
        return entry

    def close(self) -> None:
        self._file.close()

    @property
    def entries(self) -> List[LogEntry]:
        return list(self._entries)