import json
import datetime
class LogEntry:
def __init__(self, timestamp, level, message):
self.timestamp = timestamp
self.level = level
self.message = message
def to_dict(self):
return {
'timestamp': self.timestamp,
'level': self.level,
'message': self.message
}
def serialize_log_file(log_file_path, output_file_path):
"""
Serializes a log file to a JSON file.
"""
log_entries = []
try:
with open(log_file_path, 'r') as f:
for line in f:
try:
# Assuming each line represents a log entry
timestamp, level, message = line.strip().split(' ', 2)
log_entry = LogEntry(timestamp, level, message)
log_entries.append(log_entry)
except ValueError:
# Handle lines that don't match the expected format
print(f"Skipping invalid line: {line.strip()}")
except FileNotFoundError:
print(f"Error: Log file not found at {log_file_path}")
return
try:
with open(output_file_path, 'w') as outfile:
json.dump(log_entries, outfile, indent=4) # Serialize to JSON with indentation
print(f"Log file serialized to {output_file_path}")
except Exception as e:
print(f"Error writing to output file: {e}")
if __name__ == '__main__':
# Example usage:
# Create a dummy log file
with open('example.log', 'w') as f:
f.write('2023-10-27 10:00:00 INFO This is an informational message.\n')
f.write('2023-10-27 10:00:05 ERROR An error occurred.\n')
f.write('2023-10-27 10:00:10 DEBUG This is a debug message.\n')
serialize_log_file('example.log', 'output.json')
Add your comment