loglenz 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- loglens/__init__.py +6 -0
- loglens/__main__.py +10 -0
- loglens/cli.py +199 -0
- loglens/display.py +246 -0
- loglens/export.py +64 -0
- loglens/filters.py +185 -0
- loglens/parser.py +83 -0
- loglens/presets.py +41 -0
- loglens/stats.py +149 -0
- loglens/suggest.py +186 -0
- loglenz-0.1.0.dist-info/METADATA +570 -0
- loglenz-0.1.0.dist-info/RECORD +16 -0
- loglenz-0.1.0.dist-info/WHEEL +5 -0
- loglenz-0.1.0.dist-info/entry_points.txt +2 -0
- loglenz-0.1.0.dist-info/licenses/LICENSE +21 -0
- loglenz-0.1.0.dist-info/top_level.txt +1 -0
loglens/__init__.py
ADDED
loglens/__main__.py
ADDED
loglens/cli.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Command Line Interface orchestration module for LogLens.
|
|
3
|
+
|
|
4
|
+
Parses command-line arguments using argparse, coordinates parser, filter, stats,
|
|
5
|
+
export, and display pipelines, and provides user-friendly error handling.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
from contextlib import nullcontext
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
from typing import List, Optional
|
|
13
|
+
|
|
14
|
+
from rich.console import Console
|
|
15
|
+
|
|
16
|
+
from loglens import __version__
|
|
17
|
+
from loglens.display import show_stats, show_suggestion, show_table, show_unmatched
|
|
18
|
+
from loglens.export import export_rows
|
|
19
|
+
from loglens.filters import apply_filters, parse_where
|
|
20
|
+
from loglens.parser import compile_user_regex, parse_lines
|
|
21
|
+
from loglens.presets import PRESETS
|
|
22
|
+
from loglens.stats import compute_stats
|
|
23
|
+
from loglens.suggest import suggest_regex
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class _LineTracker:
|
|
27
|
+
"""Wraps an iterable of lines to track the current 1-based line number."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, stream):
|
|
30
|
+
self.stream = stream
|
|
31
|
+
self.current_line_no = 0
|
|
32
|
+
|
|
33
|
+
def __iter__(self):
|
|
34
|
+
for line_no, line in enumerate(self.stream, start=1):
|
|
35
|
+
self.current_line_no = line_no
|
|
36
|
+
yield line
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def build_arg_parser() -> argparse.ArgumentParser:
|
|
40
|
+
"""Build the command-line argument parser for LogLens."""
|
|
41
|
+
parser = argparse.ArgumentParser(
|
|
42
|
+
prog="loglens",
|
|
43
|
+
description="A fast CLI log parser that turns messy logs into structured tables.",
|
|
44
|
+
)
|
|
45
|
+
parser.add_argument(
|
|
46
|
+
"file",
|
|
47
|
+
nargs="?",
|
|
48
|
+
default=None,
|
|
49
|
+
help="Log file to parse (if omitted, reads from stdin).",
|
|
50
|
+
)
|
|
51
|
+
parser.add_argument(
|
|
52
|
+
"--preset",
|
|
53
|
+
choices=["nginx", "apache", "syslog", "generic"],
|
|
54
|
+
help="Use a pre-defined regex pattern (nginx, apache, syslog, generic).",
|
|
55
|
+
)
|
|
56
|
+
parser.add_argument(
|
|
57
|
+
"--regex",
|
|
58
|
+
type=str,
|
|
59
|
+
help="Custom regex with named capture groups, e.g. '(?P<time>\\S+) (?P<level>\\w+)'",
|
|
60
|
+
)
|
|
61
|
+
parser.add_argument(
|
|
62
|
+
"--where",
|
|
63
|
+
action="append",
|
|
64
|
+
default=[],
|
|
65
|
+
metavar="EXPR",
|
|
66
|
+
help="Filter parsed rows, e.g. --where 'status>=500' or --where 'method=POST' (repeatable).",
|
|
67
|
+
)
|
|
68
|
+
parser.add_argument(
|
|
69
|
+
"--show-unmatched",
|
|
70
|
+
action="store_true",
|
|
71
|
+
help="Display lines that did not match the regex pattern.",
|
|
72
|
+
)
|
|
73
|
+
parser.add_argument(
|
|
74
|
+
"--stats",
|
|
75
|
+
action="store_true",
|
|
76
|
+
help="Display summary statistics and metrics.",
|
|
77
|
+
)
|
|
78
|
+
parser.add_argument(
|
|
79
|
+
"--out",
|
|
80
|
+
type=str,
|
|
81
|
+
metavar="PATH",
|
|
82
|
+
help="Export parsed/filtered rows to a .csv or .json file.",
|
|
83
|
+
)
|
|
84
|
+
parser.add_argument(
|
|
85
|
+
"--limit",
|
|
86
|
+
type=int,
|
|
87
|
+
default=50,
|
|
88
|
+
metavar="N",
|
|
89
|
+
help="Maximum rows to display in table output (default: 50).",
|
|
90
|
+
)
|
|
91
|
+
parser.add_argument(
|
|
92
|
+
"--suggest",
|
|
93
|
+
type=str,
|
|
94
|
+
metavar="SAMPLE",
|
|
95
|
+
help="Suggest a regex pattern from a sample log line and exit.",
|
|
96
|
+
)
|
|
97
|
+
parser.add_argument(
|
|
98
|
+
"--version",
|
|
99
|
+
action="version",
|
|
100
|
+
version=f"loglens {__version__}",
|
|
101
|
+
help="Show program version and exit.",
|
|
102
|
+
)
|
|
103
|
+
return parser
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def run(argv: Optional[List[str]] = None) -> int:
|
|
107
|
+
"""
|
|
108
|
+
Core execution logic for LogLens CLI.
|
|
109
|
+
|
|
110
|
+
Args:
|
|
111
|
+
argv: Command-line arguments list (defaults to sys.argv[1:]).
|
|
112
|
+
|
|
113
|
+
Returns:
|
|
114
|
+
Exit code (0 on success, non-zero on failure).
|
|
115
|
+
"""
|
|
116
|
+
parser = build_arg_parser()
|
|
117
|
+
args = parser.parse_args(argv)
|
|
118
|
+
console = Console()
|
|
119
|
+
|
|
120
|
+
# 1. If --suggest: run suggestion, display, and exit 0
|
|
121
|
+
if args.suggest:
|
|
122
|
+
pattern_str = suggest_regex(args.suggest)
|
|
123
|
+
show_suggestion(pattern_str, args.suggest, console=console)
|
|
124
|
+
return 0
|
|
125
|
+
|
|
126
|
+
# 2. Require exactly one of --preset / --regex
|
|
127
|
+
if bool(args.preset) == bool(args.regex):
|
|
128
|
+
raise ValueError("Must specify exactly one of --preset or --regex.")
|
|
129
|
+
|
|
130
|
+
if args.limit < 0:
|
|
131
|
+
raise ValueError("--limit must be a non-negative integer.")
|
|
132
|
+
|
|
133
|
+
if args.preset:
|
|
134
|
+
pattern = PRESETS[args.preset]
|
|
135
|
+
else:
|
|
136
|
+
pattern = compile_user_regex(args.regex)
|
|
137
|
+
|
|
138
|
+
# 3. Open the file or read sys.stdin
|
|
139
|
+
if args.file:
|
|
140
|
+
file_ctx = open(args.file, "r", encoding="utf-8", errors="replace")
|
|
141
|
+
else:
|
|
142
|
+
if sys.stdin.isatty():
|
|
143
|
+
parser.print_help()
|
|
144
|
+
return 1
|
|
145
|
+
file_ctx = nullcontext(sys.stdin)
|
|
146
|
+
|
|
147
|
+
with file_ctx as stream:
|
|
148
|
+
tracker = _LineTracker(stream)
|
|
149
|
+
matched_rows: List[dict] = []
|
|
150
|
+
unmatched_samples = []
|
|
151
|
+
unmatched_count = 0
|
|
152
|
+
total_non_blank = 0
|
|
153
|
+
|
|
154
|
+
# 4. Run parse_lines
|
|
155
|
+
for row_dict, raw_line in parse_lines(tracker, pattern):
|
|
156
|
+
total_non_blank += 1
|
|
157
|
+
if row_dict is not None:
|
|
158
|
+
matched_rows.append(row_dict)
|
|
159
|
+
else:
|
|
160
|
+
unmatched_count += 1
|
|
161
|
+
if len(unmatched_samples) < 1000:
|
|
162
|
+
unmatched_samples.append((tracker.current_line_no, raw_line))
|
|
163
|
+
|
|
164
|
+
# 5. Apply --where filters
|
|
165
|
+
conditions = [parse_where(expr) for expr in args.where]
|
|
166
|
+
filtered_rows = list(apply_filters(matched_rows, conditions))
|
|
167
|
+
|
|
168
|
+
# 6. Depending on flags: show table, --show-unmatched, --stats, --out
|
|
169
|
+
# 7. Stats are computed over all filtered rows (before --limit)
|
|
170
|
+
if args.stats:
|
|
171
|
+
stats_data = compute_stats(
|
|
172
|
+
filtered_rows, total_lines=total_non_blank, unmatched=unmatched_count
|
|
173
|
+
)
|
|
174
|
+
show_stats(stats_data, console=console)
|
|
175
|
+
|
|
176
|
+
if args.out:
|
|
177
|
+
exported_count = export_rows(filtered_rows, args.out)
|
|
178
|
+
console.print(f"[bold green]Exported {exported_count} rows to '{args.out}'.[/bold green]")
|
|
179
|
+
|
|
180
|
+
if not args.stats and not args.out:
|
|
181
|
+
show_table(filtered_rows, total_count=len(filtered_rows), limit=args.limit, console=console)
|
|
182
|
+
|
|
183
|
+
if args.show_unmatched:
|
|
184
|
+
show_unmatched(unmatched_samples, total_unmatched=unmatched_count, limit=20, console=console)
|
|
185
|
+
|
|
186
|
+
return 0
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
190
|
+
"""Main CLI entry point with user-friendly error wrapping."""
|
|
191
|
+
err_console = Console(stderr=True)
|
|
192
|
+
try:
|
|
193
|
+
return run(argv)
|
|
194
|
+
except KeyboardInterrupt:
|
|
195
|
+
err_console.print("\n[yellow]Operation aborted by user.[/yellow]")
|
|
196
|
+
return 130
|
|
197
|
+
except (FileNotFoundError, PermissionError, ValueError) as err:
|
|
198
|
+
err_console.print(f"[bold red]Error:[/bold red] {err}")
|
|
199
|
+
return 1
|
loglens/display.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Terminal display and rendering module for LogLens using rich.
|
|
3
|
+
|
|
4
|
+
Renders parsed logs as formatted tables, unmatched lines in warning panels,
|
|
5
|
+
statistical summaries with text bar charts, and regex suggestion previews.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
10
|
+
from rich.console import Console
|
|
11
|
+
from rich.panel import Panel
|
|
12
|
+
from rich.table import Table
|
|
13
|
+
from rich.text import Text
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _format_cell_value(key: str, val: Any) -> Text:
|
|
17
|
+
"""Format and color a single table cell value based on column name and content."""
|
|
18
|
+
text_val = "" if val is None else str(val)
|
|
19
|
+
|
|
20
|
+
# Truncate long cells to 40 characters with ellipsis
|
|
21
|
+
if len(text_val) > 40:
|
|
22
|
+
display_val = text_val[:37] + "..."
|
|
23
|
+
else:
|
|
24
|
+
display_val = text_val
|
|
25
|
+
|
|
26
|
+
# Color HTTP status codes
|
|
27
|
+
if key.lower() == "status":
|
|
28
|
+
if text_val.startswith("2"):
|
|
29
|
+
return Text(display_val, style="bold green")
|
|
30
|
+
elif text_val.startswith("3"):
|
|
31
|
+
return Text(display_val, style="cyan")
|
|
32
|
+
elif text_val.startswith("4"):
|
|
33
|
+
return Text(display_val, style="yellow")
|
|
34
|
+
elif text_val.startswith("5"):
|
|
35
|
+
return Text(display_val, style="bold red")
|
|
36
|
+
|
|
37
|
+
# Color Log levels
|
|
38
|
+
if key.lower() == "level":
|
|
39
|
+
upper = text_val.upper()
|
|
40
|
+
if upper in {"ERROR", "CRITICAL", "FATAL"}:
|
|
41
|
+
return Text(display_val, style="bold red")
|
|
42
|
+
elif upper in {"WARN", "WARNING"}:
|
|
43
|
+
return Text(display_val, style="bold yellow")
|
|
44
|
+
elif upper == "INFO":
|
|
45
|
+
return Text(display_val, style="green")
|
|
46
|
+
elif upper == "DEBUG":
|
|
47
|
+
return Text(display_val, style="dim")
|
|
48
|
+
|
|
49
|
+
return Text(display_val)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def show_table(
|
|
53
|
+
rows: List[Dict[str, str]],
|
|
54
|
+
total_count: int,
|
|
55
|
+
limit: int = 50,
|
|
56
|
+
console: Optional[Console] = None,
|
|
57
|
+
) -> None:
|
|
58
|
+
"""
|
|
59
|
+
Render parsed rows in a rich table with syntax colors and cell truncation.
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
rows: Rows to display (up to limit).
|
|
63
|
+
total_count: Total count of matching rows before limit was applied.
|
|
64
|
+
limit: Row display limit.
|
|
65
|
+
console: Optional rich Console instance.
|
|
66
|
+
"""
|
|
67
|
+
if console is None:
|
|
68
|
+
console = Console()
|
|
69
|
+
|
|
70
|
+
if not rows:
|
|
71
|
+
console.print("[yellow]No matching log entries to display.[/yellow]")
|
|
72
|
+
return
|
|
73
|
+
|
|
74
|
+
# Derive column headers from the keys of the first row
|
|
75
|
+
columns = list(rows[0].keys())
|
|
76
|
+
|
|
77
|
+
table = Table(
|
|
78
|
+
title="Parsed Logs",
|
|
79
|
+
title_style="bold magenta",
|
|
80
|
+
header_style="bold cyan",
|
|
81
|
+
show_lines=False,
|
|
82
|
+
pad_edge=False,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
for col in columns:
|
|
86
|
+
table.add_column(col)
|
|
87
|
+
|
|
88
|
+
for row in rows[:limit]:
|
|
89
|
+
row_cells = [_format_cell_value(col, row.get(col, "")) for col in columns]
|
|
90
|
+
table.add_row(*row_cells)
|
|
91
|
+
|
|
92
|
+
console.print(table)
|
|
93
|
+
showing = min(len(rows), limit)
|
|
94
|
+
console.print(f"[dim]Showing {showing} of {total_count} rows[/dim]\n")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def show_unmatched(
|
|
98
|
+
unmatched_lines: List[Tuple[int, str]],
|
|
99
|
+
total_unmatched: int,
|
|
100
|
+
limit: int = 20,
|
|
101
|
+
console: Optional[Console] = None,
|
|
102
|
+
) -> None:
|
|
103
|
+
"""
|
|
104
|
+
Display lines that failed regex matching inside a red warning panel.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
unmatched_lines: List of (line_number, line_content) tuples.
|
|
108
|
+
total_unmatched: Total count of unmatched lines.
|
|
109
|
+
limit: Maximum number of unmatched lines to print.
|
|
110
|
+
console: Optional rich Console instance.
|
|
111
|
+
"""
|
|
112
|
+
if console is None:
|
|
113
|
+
console = Console()
|
|
114
|
+
|
|
115
|
+
if not unmatched_lines:
|
|
116
|
+
return
|
|
117
|
+
|
|
118
|
+
lines_text = []
|
|
119
|
+
for line_num, raw_line in unmatched_lines[:limit]:
|
|
120
|
+
lines_text.append(f"[bold yellow]Line {line_num}:[/bold yellow] {raw_line}")
|
|
121
|
+
|
|
122
|
+
if total_unmatched > limit:
|
|
123
|
+
lines_text.append(
|
|
124
|
+
f"\n[dim]... and {total_unmatched - limit} more unmatched lines (showing first {limit})[/dim]"
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
panel_content = "\n".join(lines_text)
|
|
128
|
+
panel = Panel(
|
|
129
|
+
panel_content,
|
|
130
|
+
title=f"[bold red]Unmatched Lines ({total_unmatched} total)[/bold red]",
|
|
131
|
+
border_style="red",
|
|
132
|
+
expand=False,
|
|
133
|
+
)
|
|
134
|
+
console.print(panel)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def show_stats(stats: Dict[str, Any], console: Optional[Console] = None) -> None:
|
|
138
|
+
"""
|
|
139
|
+
Display statistical summary panel and sub-tables for each detected metric.
|
|
140
|
+
|
|
141
|
+
Includes a text bar chart for errors_per_minute scaled to 30 characters.
|
|
142
|
+
|
|
143
|
+
Args:
|
|
144
|
+
stats: Dictionary of statistics produced by stats.compute_stats().
|
|
145
|
+
console: Optional rich Console instance.
|
|
146
|
+
"""
|
|
147
|
+
if console is None:
|
|
148
|
+
console = Console()
|
|
149
|
+
|
|
150
|
+
# Overview panel
|
|
151
|
+
summary_text = (
|
|
152
|
+
f"[bold]Total Non-Empty Lines:[/bold] {stats.get('total_lines', 0)}\n"
|
|
153
|
+
f"[bold green]Matched Rows:[/bold green] {stats.get('matched', 0)}\n"
|
|
154
|
+
f"[bold red]Unmatched Lines:[/bold red] {stats.get('unmatched', 0)}\n"
|
|
155
|
+
f"[bold cyan]Match Rate:[/bold cyan] {stats.get('match_rate', 0.0)}%"
|
|
156
|
+
)
|
|
157
|
+
console.print(
|
|
158
|
+
Panel(summary_text, title="[bold blue]LogLens Statistics Overview[/bold blue]", border_style="blue", expand=False)
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
# Top IPs
|
|
162
|
+
if "top_ips" in stats and stats["top_ips"]:
|
|
163
|
+
ip_table = Table(title="Top 5 Client IPs", header_style="bold green")
|
|
164
|
+
ip_table.add_column("IP Address", style="bold")
|
|
165
|
+
ip_table.add_column("Requests", justify="right")
|
|
166
|
+
for ip, count in stats["top_ips"]:
|
|
167
|
+
ip_table.add_row(ip, str(count))
|
|
168
|
+
console.print(ip_table)
|
|
169
|
+
|
|
170
|
+
# Status counts
|
|
171
|
+
if "status_counts" in stats and stats["status_counts"]:
|
|
172
|
+
status_table = Table(title="HTTP Status Code Distribution", header_style="bold yellow")
|
|
173
|
+
status_table.add_column("Status Code", style="bold")
|
|
174
|
+
status_table.add_column("Count", justify="right")
|
|
175
|
+
for sc, count in stats["status_counts"].items():
|
|
176
|
+
status_table.add_row(_format_cell_value("status", sc), str(count))
|
|
177
|
+
console.print(status_table)
|
|
178
|
+
|
|
179
|
+
# Top Paths
|
|
180
|
+
if "top_paths" in stats and stats["top_paths"]:
|
|
181
|
+
path_table = Table(title="Top 5 Requested Paths", header_style="bold magenta")
|
|
182
|
+
path_table.add_column("Path", style="bold")
|
|
183
|
+
path_table.add_column("Count", justify="right")
|
|
184
|
+
for p, count in stats["top_paths"]:
|
|
185
|
+
path_table.add_row(p, str(count))
|
|
186
|
+
console.print(path_table)
|
|
187
|
+
|
|
188
|
+
# Level counts
|
|
189
|
+
if "level_counts" in stats and stats["level_counts"]:
|
|
190
|
+
level_table = Table(title="Log Level Distribution", header_style="bold cyan")
|
|
191
|
+
level_table.add_column("Level", style="bold")
|
|
192
|
+
level_table.add_column("Count", justify="right")
|
|
193
|
+
for lvl, count in stats["level_counts"].items():
|
|
194
|
+
level_table.add_row(_format_cell_value("level", lvl), str(count))
|
|
195
|
+
console.print(level_table)
|
|
196
|
+
|
|
197
|
+
# Errors per minute text bar chart
|
|
198
|
+
if "errors_per_minute" in stats and stats["errors_per_minute"]:
|
|
199
|
+
epm = stats["errors_per_minute"]
|
|
200
|
+
max_err = max(epm.values()) if epm else 1
|
|
201
|
+
err_table = Table(title="Errors Per Minute (Status >= 500 or ERROR/CRITICAL/FATAL)", header_style="bold red")
|
|
202
|
+
err_table.add_column("Minute Window", style="bold")
|
|
203
|
+
err_table.add_column("Count", justify="right")
|
|
204
|
+
err_table.add_column("Distribution")
|
|
205
|
+
|
|
206
|
+
for minute_win, count in epm.items():
|
|
207
|
+
# Scale bar up to 30 characters
|
|
208
|
+
bar_len = int(round((count / max_err) * 30))
|
|
209
|
+
bar_str = "█" * max(1, bar_len)
|
|
210
|
+
err_table.add_row(minute_win, str(count), f"[red]{bar_str}[/red]")
|
|
211
|
+
console.print(err_table)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def show_suggestion(regex_pattern: str, sample_line: str, console: Optional[Console] = None) -> None:
|
|
215
|
+
"""
|
|
216
|
+
Display the suggested regex pattern and the extracted capture groups.
|
|
217
|
+
|
|
218
|
+
Args:
|
|
219
|
+
regex_pattern: The generated regular expression string.
|
|
220
|
+
sample_line: The sample line it was derived from.
|
|
221
|
+
console: Optional rich Console instance.
|
|
222
|
+
"""
|
|
223
|
+
if console is None:
|
|
224
|
+
console = Console()
|
|
225
|
+
|
|
226
|
+
console.print(
|
|
227
|
+
Panel(
|
|
228
|
+
Text(regex_pattern, style="bold green"),
|
|
229
|
+
title="[bold]Suggested Regular Expression[/bold]",
|
|
230
|
+
border_style="green",
|
|
231
|
+
expand=False,
|
|
232
|
+
)
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
try:
|
|
236
|
+
compiled = re.compile(regex_pattern)
|
|
237
|
+
m = compiled.match(sample_line)
|
|
238
|
+
if m:
|
|
239
|
+
group_table = Table(title="Extracted Named Groups from Sample", header_style="bold cyan")
|
|
240
|
+
group_table.add_column("Group Name", style="bold")
|
|
241
|
+
group_table.add_column("Extracted Value")
|
|
242
|
+
for name, val in m.groupdict().items():
|
|
243
|
+
group_table.add_row(name, str(val) if val is not None else "")
|
|
244
|
+
console.print(group_table)
|
|
245
|
+
except re.error:
|
|
246
|
+
pass
|
loglens/export.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Data export module for LogLens.
|
|
3
|
+
|
|
4
|
+
Exports parsed log records to CSV or JSON formats.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import csv
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
from typing import Dict, Iterable
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def export_rows(rows: Iterable[Dict[str, str]], path: str) -> int:
|
|
14
|
+
"""
|
|
15
|
+
Write parsed rows to the specified file path.
|
|
16
|
+
|
|
17
|
+
The format is determined by the file extension (.csv or .json).
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
rows: Iterable of row dictionaries.
|
|
21
|
+
path: Output file path.
|
|
22
|
+
|
|
23
|
+
Returns:
|
|
24
|
+
Number of rows exported.
|
|
25
|
+
|
|
26
|
+
Raises:
|
|
27
|
+
ValueError: If the file extension is not .csv or .json.
|
|
28
|
+
"""
|
|
29
|
+
lower_path = path.lower()
|
|
30
|
+
if not (lower_path.endswith(".csv") or lower_path.endswith(".json")):
|
|
31
|
+
raise ValueError(
|
|
32
|
+
f"Unsupported export format for '{path}'. Supported formats are .csv and .json"
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
# Ensure parent directory exists if a directory path was provided
|
|
36
|
+
dirname = os.path.dirname(path)
|
|
37
|
+
if dirname:
|
|
38
|
+
os.makedirs(dirname, exist_ok=True)
|
|
39
|
+
|
|
40
|
+
if lower_path.endswith(".csv"):
|
|
41
|
+
iterator = iter(rows)
|
|
42
|
+
try:
|
|
43
|
+
first_row = next(iterator)
|
|
44
|
+
except StopIteration:
|
|
45
|
+
# Empty rows: create an empty file
|
|
46
|
+
with open(path, "w", newline="", encoding="utf-8"):
|
|
47
|
+
pass
|
|
48
|
+
return 0
|
|
49
|
+
|
|
50
|
+
with open(path, "w", newline="", encoding="utf-8") as f:
|
|
51
|
+
writer = csv.DictWriter(f, fieldnames=list(first_row.keys()))
|
|
52
|
+
writer.writeheader()
|
|
53
|
+
writer.writerow(first_row)
|
|
54
|
+
count = 1
|
|
55
|
+
for row in iterator:
|
|
56
|
+
writer.writerow(row)
|
|
57
|
+
count += 1
|
|
58
|
+
return count
|
|
59
|
+
|
|
60
|
+
else: # .json
|
|
61
|
+
rows_list = list(rows)
|
|
62
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
63
|
+
json.dump(rows_list, f, indent=2, ensure_ascii=False)
|
|
64
|
+
return len(rows_list)
|