1. import time
  2. import logging
  3. import sys
  4. def watch_log(log_file, filter_string=""):
  5. """Watches a log file for changes and prints new entries."""
  6. try:
  7. # Set up the logger
  8. logger = logging.getLogger()
  9. logger.setLevel(logging.DEBUG) # Adjust as needed
  10. # Create a handler to output to the console
  11. handler = logging.StreamHandler(sys.stdout)
  12. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  13. handler.setFormatter(formatter)
  14. logger.addHandler(handler)
  15. # Initial state: read all lines from the file
  16. with open(log_file, 'r') as f:
  17. existing_lines = set(f.readlines())
  18. # Watch for changes
  19. while True:
  20. try:
  21. time.sleep(1) # Check for changes every second
  22. with open(log_file, 'r') as f:
  23. current_lines = set(f.readlines())
  24. # Find new lines
  25. new_lines = current_lines - existing_lines
  26. # Print new lines
  27. for line in new_lines:
  28. print(line, end='') # Print without adding extra newline
  29. # Update existing lines
  30. existing_lines = current_lines
  31. except FileNotFoundError:
  32. print(f"Error: Log file '{log_file}' not found.")
  33. break # Exit if the file is not found
  34. except Exception as e:
  35. print(f"An error occurred: {e}")
  36. break
  37. except Exception as e:
  38. print(f"An error occurred: {e}")
  39. if __name__ == "__main__":
  40. if len(sys.argv) != 2:
  41. print("Usage: python watch_log.py <log_file>")
  42. sys.exit(1)
  43. log_file = sys.argv[1]
  44. watch_log(log_file)

Add your comment