import time
import logging
import sys
def watch_log(log_file, filter_string=""):
"""Watches a log file for changes and prints new entries."""
try:
# Set up the logger
logger = logging.getLogger()
logger.setLevel(logging.DEBUG) # Adjust as needed
# Create a handler to output to the console
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
# Initial state: read all lines from the file
with open(log_file, 'r') as f:
existing_lines = set(f.readlines())
# Watch for changes
while True:
try:
time.sleep(1) # Check for changes every second
with open(log_file, 'r') as f:
current_lines = set(f.readlines())
# Find new lines
new_lines = current_lines - existing_lines
# Print new lines
for line in new_lines:
print(line, end='') # Print without adding extra newline
# Update existing lines
existing_lines = current_lines
except FileNotFoundError:
print(f"Error: Log file '{log_file}' not found.")
break # Exit if the file is not found
except Exception as e:
print(f"An error occurred: {e}")
break
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python watch_log.py <log_file>")
sys.exit(1)
log_file = sys.argv[1]
watch_log(log_file)
Add your comment