🔍 Code Extractor

function tail_logs

Maturity: 42

Reads and displays the last N lines from a specified log file, with error handling for missing files and read failures.

File:
/tf/active/vicechatdev/SPFCsync/monitor.py
Lines:
157 - 174
Complexity:
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

    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.

    From: /tf/active/vicechatdev/SPFCsync/monitor.py
  • function main_v18 44.1% similar

    Command-line interface entry point for monitoring SharePoint to FileCloud synchronization logs, providing status analysis, log tailing, and real-time watching capabilities.

    From: /tf/active/vicechatdev/SPFCsync/monitor.py
  • function parse_log_line 39.2% similar

    Parses a structured log line string and extracts timestamp, logger name, log level, and message components into a dictionary.

    From: /tf/active/vicechatdev/SPFCsync/monitor.py
  • function analyze_logs 38.9% similar

    Parses and analyzes log files to extract synchronization statistics, error counts, and performance metrics for a specified time period.

    From: /tf/active/vicechatdev/SPFCsync/monitor.py
  • function show_problematic_flocks 35.1% similar

    Analyzes and displays problematic flocks from a dataset by identifying those with systematic timing issues in their treatment records, categorizing them by severity and volume.

    From: /tf/active/vicechatdev/data_quality_dashboard.py
← Back to Browse