36 lines
951 B
Python
Raw Normal View History

2024-12-20 16:33:06 +09:00
import json
2024-11-18 10:31:27 +09:00
import sys
from collections.abc import Iterable
from typing import Optional
2024-12-20 23:36:22 +09:00
TOPIC_LOG_INDICATOR = '{"topic":'
2024-11-18 10:31:27 +09:00
2024-12-20 16:33:06 +09:00
def line_to_json_stream(record_stream: Iterable[str]) -> Iterable[tuple[str, dict]]:
2024-11-18 10:31:27 +09:00
for record in record_stream:
2024-12-20 23:36:22 +09:00
topic_idx = record.find(TOPIC_LOG_INDICATOR)
2024-12-20 16:33:06 +09:00
if topic_idx == -1:
continue
# Split the line into 2 parts: topic and JSON message
2024-12-20 23:36:22 +09:00
log = json.loads(record[topic_idx:].strip())
yield (log["topic"], log["message"])
2024-11-18 10:31:27 +09:00
def get_pipe_stream() -> Iterable[str]:
yield from sys.stdin
def get_file_stream(input_filename) -> Iterable[str]:
with open(input_filename, "r") as file:
yield from file
2024-12-20 16:33:06 +09:00
def get_input_stream(input_filename: Optional[str]) -> Iterable[tuple[str, dict]]:
2024-11-18 10:31:27 +09:00
stream = (
get_file_stream(input_filename)
if input_filename is not None
else get_pipe_stream()
)
return line_to_json_stream(stream)