import re
def diagnose_file(filepath, patterns):
"""
Matches patterns in a file content and returns matching patterns.
Args:
filepath (str): The path to the file.
patterns (dict): A dictionary where keys are pattern names and values are regular expressions.
Returns:
dict: A dictionary where keys are pattern names and values are lists of matched lines.
Returns an empty dictionary if the file doesn't exist or an error occurs.
"""
try:
with open(filepath, 'r') as f:
content = f.read()
except FileNotFoundError:
print(f"Error: File not found at {filepath}")
return {}
except Exception as e:
print(f"Error reading file: {e}")
return {}
results = {}
for name, pattern in patterns.items():
results[name] = re.findall(pattern, content, re.MULTILINE)
return results
if __name__ == '__main__':
# Example usage
patterns = {
"error_messages": r"ERROR: (.*)", # Matches lines starting with "ERROR:"
"warning_messages": r"WARNING: (.*)", # Matches lines starting with "WARNING:"
"log_level": r"log_level=(.*)" # Matches lines containing "log_level="
}
filepath = "example.log" # Replace with your file path
# Create a dummy log file for testing
with open(filepath, "w") as f:
f.write("This is a normal log line.\n")
f.write("ERROR: Something went wrong.\n")
f.write("WARNING: Low disk space.\n")
f.write("log_level=INFO\n")
f.write("Another normal log line.\n")
f.write("ERROR: Another error occurred.\n")
f.write("WARNING: Memory usage is high.\n")
diagnostics = diagnose_file(filepath, patterns)
for name, matches in diagnostics.items():
if matches:
print(f"Pattern: {name}")
for match in matches:
print(match)
else:
print(f"Pattern: {name} - No matches found.")
Add your comment