1. import time
  2. import os
  3. import logging
  4. def stream_log_files(log_file_patterns, interval=60, output_file="streamed_logs.txt"):
  5. """
  6. Streams data from log files matching specified patterns.
  7. Args:
  8. log_file_patterns (list): A list of file patterns to monitor (e.g., ["*.log", "app*.txt"]).
  9. interval (int): Polling interval in seconds.
  10. output_file (str): File to write the streamed log data to.
  11. """
  12. logging.basicConfig(level=logging.INFO)
  13. while True:
  14. try:
  15. for pattern in log_file_patterns:
  16. for filename in glob.glob(pattern): #using glob for file matching
  17. try:
  18. with open(filename, 'r', encoding='utf-8') as f:
  19. for line in f:
  20. logged_message = f"{time.strftime('%Y-%m-%d %H:%M:%S')} - {filename}: {line.strip()}\n" #Timestamp and filename
  21. with open(output_file, 'a') as outfile:
  22. outfile.write(logged_message)
  23. logging.info(f"Logged from {filename}") # Log to console
  24. except FileNotFoundError:
  25. logging.warning(f"File not found: {filename}")
  26. except Exception as e:
  27. logging.error(f"Error reading {filename}: {e}")
  28. time.sleep(interval) # Wait before next check
  29. except Exception as e:
  30. logging.error(f"An error occurred: {e}")
  31. time.sleep(interval)
  32. import glob #Import glob for file matching
  33. if __name__ == "__main__":
  34. log_patterns = ["*.log"] #Example: monitor all .log files
  35. stream_log_files(log_patterns, interval=10, output_file="streamed_logs.txt")

Add your comment