Goal: Implement a small utility that finds the most recently modified log file in a given directory whose filename matches a provided regular expression. This task focuses on a single, straightforward behavior: scan a directory (non-recursively), filter by a regex, and return the path to the latest file by modification time. If no file matches, return None.
What to implement
Create a function with the following signature:
def task_func(pattern, log_dir='/var/log/'):
Returns: str or None
The absolute path to the most recently modified file in log_dir whose filename matches pattern, or None if there are no matches.
The function should be self-contained and exportable.
Notes and constraints
Only consider files directly inside log_dir (no subdirectories required).
Use Python's re module to interpret the pattern.
If log_dir does not exist or contains no matching files, return None.
The function should be robust to invalid regex patterns by returning None.
Skeleton to guide you (optional but recommended)
text
import os
import re
def task_func(pattern, log_dir='/var/log/'):
# Skeleton: compile the regex, iterate over files in log_dir,
# filter by name using the regex, track the latest by modification time.
return None
Hints
Use os.listdir(log_dir) to list items, and os.path.join(log_dir, name) to get full paths.
Skip items that are not regular files (use os.path.isfile).
Use os.path.getmtime(full_path) to compare modification times.
Be mindful of potential FileNotFoundError if log_dir is missing.
What to submit
Place your solution in /app/ and export the required function(s).
Provide a complete, self-contained implementation of task_func with the described behavior.