Wednesday, 15 July 2020

Python Log Parser

We all know how tedious it is to vi a log or trace and search for strings in it. Not to mention to remember the correct awk and sed syntax which we always tend to forget in times of emergency.

Given below is a very crude python log parser where the user supplies the entire path and file name and the text string to search for.

The output is the search string and the number of occurrences of it.

For windows users, when entering the path, use / instead of \ i.e C:\users becomes C:/users.

save the code as a .py file and try it out.

>> Python file parsing code.



#importing regular expression package
import re
#asking user to give full path name and file name
log_file_name = input ("Enter the log file path and name: ")

expression_to_search = input("Enter the error to search: ")

match_array = []
with open(log_file_name, "r") as file:
    for line in file:
        for match in re.finditer(expression_to_search, line, re.S):
            match_text = match.group()
            match_array.append(match_text)
            print (match_text)
            print (match_array.count(expression_to_search))

Happy Parsing :)

No comments:

Post a Comment