Files
loglens-cli/loglens/formatters/json_formatter.py
7000pctAUTO 0caa7c9585
Some checks failed
CI / test (3.11) (push) Has been cancelled
CI / test (3.12) (push) Has been cancelled
CI / test (3.9) (push) Has been cancelled
CI / lint (push) Has been cancelled
CI / build (push) Has been cancelled
CI / test (3.10) (push) Has been cancelled
Add formatters (table, JSON, text)
2026-02-02 10:09:26 +00:00

58 lines
2.0 KiB
Python

"""JSON output formatter."""
import json
from typing import Any
from loglens.analyzers.analyzer import AnalysisResult
from loglens.formatters.base import OutputFormatter
from loglens.parsers.base import ParsedLogEntry
class JSONFormatter(OutputFormatter):
"""Formats output as JSON."""
def format(self, data: Any) -> str:
"""Format data as JSON."""
if isinstance(data, AnalysisResult):
return self._format_analysis_result(data)
elif isinstance(data, list):
return self._format_entries(data)
else:
return json.dumps(data, default=str, indent=2)
def _format_analysis_result(self, result: AnalysisResult) -> str:
"""Format analysis result as JSON."""
output = {
"summary": {
"total_lines": result.total_lines,
"parsed_entries": result.parsed_count,
"format_detected": result.format_detected.value,
"analysis_time": result.analysis_time.isoformat(),
},
"severity_breakdown": result.severity_breakdown,
"pattern_matches": result.pattern_matches,
"top_errors": result.top_errors,
"host_breakdown": result.host_breakdown,
"suggestions": result.suggestions,
}
if result.time_range:
output["time_range"] = {
"start": result.time_range[0].isoformat(),
"end": result.time_range[1].isoformat(),
}
return json.dumps(output, default=str, indent=2)
def _format_entries(self, entries: list[ParsedLogEntry]) -> str:
"""Format log entries as JSON array."""
output = [entry.to_dict() for entry in entries]
return json.dumps(output, default=str, indent=2)
def format_entries_compact(self, entries: list[ParsedLogEntry]) -> str:
"""Format entries as compact JSON (one per line)."""
lines = []
for entry in entries:
lines.append(json.dumps(entry.to_dict(), default=str))
return "\n".join(lines)