function watch_logs
Monitors a log file in real-time and continuously prints new entries as they are appended to the file, similar to the Unix 'tail -f' command.
/tf/active/vicechatdev/SPFCsync/monitor.py
176 - 200
simple
Purpose
This function provides real-time log monitoring capabilities by watching a specified log file and displaying new entries as they are written. It's useful for debugging, monitoring application behavior, or tracking system events in real-time. The function handles file existence checks, graceful shutdown via keyboard interrupt, and error handling for file access issues.
Source Code
def watch_logs(log_file):
"""Watch log file for new entries."""
if not os.path.exists(log_file):
print(f"Log file {log_file} not found")
return
print(f"Watching {log_file} for new entries (Press Ctrl+C to stop)...")
print("-" * 50)
try:
with open(log_file, 'r') as f:
# Go to end of file
f.seek(0, 2)
while True:
line = f.readline()
if line:
print(line.rstrip())
else:
time.sleep(1)
except KeyboardInterrupt:
print("\nStopped watching logs")
except Exception as e:
print(f"Error watching log file: {e}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
log_file |
- | - | positional_or_keyword |
Parameter Details
log_file: String path to the log file to monitor. Can be an absolute or relative file path. The file must exist before monitoring begins, otherwise the function will print an error message and return early.
Return Value
Returns None. The function does not return a value but instead runs continuously until interrupted by the user (Ctrl+C) or an error occurs. It prints log entries to stdout as they appear in the file.
Dependencies
ostime
Required Imports
import os
import time
Usage Example
import os
import time
# Create a sample log file for demonstration
log_path = '/var/log/myapp.log'
# Watch the log file (will run until Ctrl+C is pressed)
watch_logs(log_path)
# Example with relative path
watch_logs('./application.log')
# The function will output:
# Watching ./application.log for new entries (Press Ctrl+C to stop)...
# --------------------------------------------------
# [2024-01-15 10:30:45] Application started
# [2024-01-15 10:30:46] Processing request...
# (continues until interrupted)
Best Practices
- Ensure the log file exists before calling this function to avoid immediate termination
- Use Ctrl+C to gracefully stop watching the log file
- Be aware that this function runs indefinitely until interrupted, so it should be used in appropriate contexts (CLI tools, debugging sessions)
- The function uses a 1-second polling interval which may not be suitable for high-frequency log updates; consider adjusting time.sleep() for different use cases
- The function seeks to the end of the file (f.seek(0, 2)) so it only shows new entries, not existing content
- Ensure proper file permissions are set for reading the log file
- Consider using this function in a separate thread or process if integrating into a larger application to avoid blocking the main execution flow
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function tail_logs 70.0% similar
-
function main_v18 55.1% similar
-
function analyze_logs 46.0% similar
-
function parse_log_line 37.6% similar
-
class ActivityLogger 36.1% similar