import re
import logging
import os
from datetime import datetime
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def transform_log_data(log_file_path, output_file_path, transform_function):
"""
Transforms data from a log file and writes it to an output file.
Handles potential errors gracefully.
Args:
log_file_path (str): Path to the input log file.
output_file_path (str): Path to the output file.
transform_function (callable): A function that takes a log line as input
and returns the transformed data.
"""
try:
with open(log_file_path, 'r') as infile, open(output_file_path, 'w') as outfile:
for line in infile:
try:
# Apply the transformation function
transformed_data = transform_function(line)
if transformed_data: # Only write if transformation was successful
outfile.write(transformed_data + '\n')
except Exception as e:
logging.error(f"Error processing line: {line.strip()} - {e}")
except FileNotFoundError:
logging.error(f"Log file not found: {log_file_path}")
except Exception as e:
logging.error(f"An unexpected error occurred: {e}")
def example_transform(log_line):
"""
Example transformation function. Extracts timestamp and message.
Args:
log_line (str): A single line from the log file.
Returns:
str: The transformed data (timestamp, message) or None if transformation fails.
"""
try:
# Example regex to extract timestamp and message
match = re.match(r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).*?(?=\n|$)', log_line)
if match:
timestamp = match.group(1)
message = match.group(0).replace(timestamp, "").strip()
return f"{timestamp}, {message}"
else:
return None # Indicate failure
except Exception as e:
logging.error(f"Error in example transform: {e}")
return None
if __name__ == '__main__':
#Example usage
log_file = 'input.log'
output_file = 'output.txt'
# Create a dummy input log file for testing
with open(log_file, 'w') as f:
f.write("2023-10-27 10:00:00 This is a log message.\n")
f.write("2023-10-27 10:00:05 Another log message.\n")
f.write("Invalid log line\n") #Example of an invalid line.
f.write("2023-10-27 10:00:10 Final log message.\n")
transform_log_data(log_file, output_file, example_transform)
logging.info(f"Data transformation complete. Output written to {output_file}")
Add your comment