Add formatters: table, JSON, text and config
Some checks failed
Some checks failed
This commit is contained in:
57
loglens/formatters/json_formatter.py
Normal file
57
loglens/formatters/json_formatter.py
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
"""JSON output formatter."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
|
from loglens.analyzers.analyzer import AnalysisResult
|
||||||
|
from loglens.parsers.base import ParsedLogEntry
|
||||||
|
from loglens.formatters.base import OutputFormatter
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
Reference in New Issue
Block a user