1. import re
  2. import logging
  3. import os
  4. from datetime import datetime
  5. # Configure logging
  6. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  7. def transform_log_data(log_file_path, output_file_path, transform_function):
  8. """
  9. Transforms data from a log file and writes it to an output file.
  10. Handles potential errors gracefully.
  11. Args:
  12. log_file_path (str): Path to the input log file.
  13. output_file_path (str): Path to the output file.
  14. transform_function (callable): A function that takes a log line as input
  15. and returns the transformed data.
  16. """
  17. try:
  18. with open(log_file_path, 'r') as infile, open(output_file_path, 'w') as outfile:
  19. for line in infile:
  20. try:
  21. # Apply the transformation function
  22. transformed_data = transform_function(line)
  23. if transformed_data: # Only write if transformation was successful
  24. outfile.write(transformed_data + '\n')
  25. except Exception as e:
  26. logging.error(f"Error processing line: {line.strip()} - {e}")
  27. except FileNotFoundError:
  28. logging.error(f"Log file not found: {log_file_path}")
  29. except Exception as e:
  30. logging.error(f"An unexpected error occurred: {e}")
  31. def example_transform(log_line):
  32. """
  33. Example transformation function. Extracts timestamp and message.
  34. Args:
  35. log_line (str): A single line from the log file.
  36. Returns:
  37. str: The transformed data (timestamp, message) or None if transformation fails.
  38. """
  39. try:
  40. # Example regex to extract timestamp and message
  41. match = re.match(r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).*?(?=\n|$)', log_line)
  42. if match:
  43. timestamp = match.group(1)
  44. message = match.group(0).replace(timestamp, "").strip()
  45. return f"{timestamp}, {message}"
  46. else:
  47. return None # Indicate failure
  48. except Exception as e:
  49. logging.error(f"Error in example transform: {e}")
  50. return None
  51. if __name__ == '__main__':
  52. #Example usage
  53. log_file = 'input.log'
  54. output_file = 'output.txt'
  55. # Create a dummy input log file for testing
  56. with open(log_file, 'w') as f:
  57. f.write("2023-10-27 10:00:00 This is a log message.\n")
  58. f.write("2023-10-27 10:00:05 Another log message.\n")
  59. f.write("Invalid log line\n") #Example of an invalid line.
  60. f.write("2023-10-27 10:00:10 Final log message.\n")
  61. transform_log_data(log_file, output_file, example_transform)
  62. logging.info(f"Data transformation complete. Output written to {output_file}")

Add your comment