1. import json
  2. import datetime
  3. class LogEntry:
  4. def __init__(self, timestamp, level, message):
  5. self.timestamp = timestamp
  6. self.level = level
  7. self.message = message
  8. def to_dict(self):
  9. return {
  10. 'timestamp': self.timestamp,
  11. 'level': self.level,
  12. 'message': self.message
  13. }
  14. def serialize_log_file(log_file_path, output_file_path):
  15. """
  16. Serializes a log file to a JSON file.
  17. """
  18. log_entries = []
  19. try:
  20. with open(log_file_path, 'r') as f:
  21. for line in f:
  22. try:
  23. # Assuming each line represents a log entry
  24. timestamp, level, message = line.strip().split(' ', 2)
  25. log_entry = LogEntry(timestamp, level, message)
  26. log_entries.append(log_entry)
  27. except ValueError:
  28. # Handle lines that don't match the expected format
  29. print(f"Skipping invalid line: {line.strip()}")
  30. except FileNotFoundError:
  31. print(f"Error: Log file not found at {log_file_path}")
  32. return
  33. try:
  34. with open(output_file_path, 'w') as outfile:
  35. json.dump(log_entries, outfile, indent=4) # Serialize to JSON with indentation
  36. print(f"Log file serialized to {output_file_path}")
  37. except Exception as e:
  38. print(f"Error writing to output file: {e}")
  39. if __name__ == '__main__':
  40. # Example usage:
  41. # Create a dummy log file
  42. with open('example.log', 'w') as f:
  43. f.write('2023-10-27 10:00:00 INFO This is an informational message.\n')
  44. f.write('2023-10-27 10:00:05 ERROR An error occurred.\n')
  45. f.write('2023-10-27 10:00:10 DEBUG This is a debug message.\n')
  46. serialize_log_file('example.log', 'output.json')

Add your comment