Add formatters (table, JSON, text)
Some checks failed
Some checks failed
This commit is contained in:
@@ -1,14 +1,57 @@
|
|||||||
|
"""JSON output formatter."""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from loglens.analyzers.analyzer import AnalysisResult
|
from loglens.analyzers.analyzer import AnalysisResult
|
||||||
|
from loglens.formatters.base import OutputFormatter
|
||||||
|
from loglens.parsers.base import ParsedLogEntry
|
||||||
|
|
||||||
|
|
||||||
class JSONFormatter:
|
class JSONFormatter(OutputFormatter):
|
||||||
"""Format analysis results as JSON."""
|
"""Formats output as JSON."""
|
||||||
|
|
||||||
def format(self, result: Any) -> str:
|
def format(self, data: Any) -> str:
|
||||||
"""Format result as JSON."""
|
"""Format data as JSON."""
|
||||||
if hasattr(result, "to_dict"):
|
if isinstance(data, AnalysisResult):
|
||||||
return json.dumps(result.to_dict(), indent=2)
|
return self._format_analysis_result(data)
|
||||||
return json.dumps(result, indent=2)
|
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)
|
||||||
|
|||||||
Reference in New Issue
Block a user