function tail_logs
Reads and displays the last N lines from a specified log file, with error handling for missing files and read failures.
/tf/active/vicechatdev/SPFCsync/monitor.py
157 - 174
simple
Purpose
This function provides a tail-like utility for viewing recent log entries from a file. It's useful for debugging, monitoring application behavior, or quickly checking the most recent events without opening the entire log file. The function handles edge cases like non-existent files and files with fewer lines than requested.
Source Code
def tail_logs(log_file, lines=50):
"""Display the last N lines of the log file."""
if not os.path.exists(log_file):
print(f"Log file {log_file} not found")
return
try:
with open(log_file, 'r') as f:
all_lines = f.readlines()
recent_lines = all_lines[-lines:] if len(all_lines) >= lines else all_lines
print(f"Last {len(recent_lines)} log entries:")
print("-" * 50)
for line in recent_lines:
print(line.rstrip())
except Exception as e:
print(f"Error reading log file: {e}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
log_file |
- | - | positional_or_keyword |
lines |
- | 50 | positional_or_keyword |
Parameter Details
log_file: String path to the log file to read. Can be absolute or relative path. The function checks if this file exists before attempting to read it.
lines: Integer specifying the number of most recent lines to display from the log file. Defaults to 50. If the file contains fewer lines than specified, all available lines are displayed.
Return Value
This function returns None (implicit). It produces side effects by printing output directly to stdout, including the log entries, error messages if the file is not found, or exception messages if reading fails.
Dependencies
os
Required Imports
import os
Usage Example
import os
# Example 1: Display last 50 lines (default)
tail_logs('/var/log/application.log')
# Example 2: Display last 100 lines
tail_logs('/var/log/application.log', lines=100)
# Example 3: Display last 10 lines from a relative path
tail_logs('logs/debug.log', lines=10)
# Example 4: Handle non-existent file (will print error message)
tail_logs('/path/to/nonexistent.log')
Best Practices
- Ensure the log file path is valid and accessible before calling this function
- Be cautious with the 'lines' parameter for very large log files, as the function reads the entire file into memory
- For production use with very large log files (>100MB), consider using more memory-efficient approaches like reading from the end of the file
- The function strips trailing whitespace from each line using rstrip(), which may affect formatting if trailing spaces are significant
- This function prints directly to stdout; consider refactoring to return lines as a list if you need programmatic access to the log content
- The function catches all exceptions broadly; in production code, you may want more specific exception handling
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function watch_logs 70.0% similar
-
function main_v18 44.1% similar
-
function parse_log_line 39.2% similar
-
function analyze_logs 38.9% similar
-
function show_problematic_flocks 35.1% similar