Parse a Log File in Python with Generators
To parse a log file in Python without loading all of it, build a pipeline of generators. One stage reads lines, one splits them into fields and one filters. Only one line is in memory at a time.
Prerequisites: Python Read File Line by Line with a Generator, Python Generator Pipeline and Unpacking. Each example writes a small web-server log first, so it runs on its own. Each line holds a page, a status code and a response time in milliseconds.
Read, split and filter in separate stages
Give every stage one job and one input.
with open("access.log", "w") as target: target.write("/home 200 35\n/login 500 410\n/about 200 20\n/cart 404 15\n")def read_lines(path): with open(path) as file: for line in file: yield line.rstrip("\n")def requests(lines): for line in lines: page, status, time = line.split() yield page, int(status), int(time)def failed(rows): for page, status, time in rows: if status >= 400: yield page, statusfor page, status in failed(requests(read_lines("access.log"))): print(page, status)This prints /login 500, then /cart 404. requests() turns text into a tuple of typed values. failed() never touches text at all.
Finish a pipeline with sum(), max() or any()
A pipeline does nothing until something consumes it. A loop is one consumer; these functions are others.
with open("access.log", "w") as target: target.write("/home 200 35\n/login 500 410\n/about 200 20\n/cart 404 15\n")def read_lines(path): with open(path) as file: for line in file: print("read:", line.rstrip("\n")) yield line.rstrip("\n")def requests(lines): for line in lines: page, status, time = line.split() yield page, int(status), int(time)rows = requests(read_lines("access.log"))print(any(status == 500 for page, status, time in rows))Two read: lines print, then True. any() stops at the first match, so the last two lines are never read. sum() and max() have to read to the end.
Check a stage with a small sample
To debug a pipeline, look at the first few items of one stage with islice().
from itertools import islicewith open("access.log", "w") as target: target.write("/home 200 35\n/login 500 410\n/about 200 20\n/cart 404 15\n")def read_lines(path): with open(path) as file: for line in file: yield line.rstrip("\n")def requests(lines): for line in lines: page, status, time = line.split() yield page, int(status), int(time)rows = requests(read_lines("access.log"))print(list(islice(rows, 2)))print(list(rows))The first list holds two tuples. The second holds only the other two: the sample used up part of rows. Build the pipeline again after sampling it.
Keep every stage lazy
One eager step undoes the saving. sorted(rows), list(rows) and file.readlines() all load everything. Sort or store only the small result at the end of the pipeline.
A broken line stops the pipeline
These stages assume every line has three fields. A line with fewer raises an error, but only when the pipeline reaches it.
with open("access.log", "w") as target: target.write("/home 200 35\n/login 500\n/about 200 20\n")def read_lines(path): with open(path) as file: for line in file: yield line.rstrip("\n")def requests(lines): for line in lines: page, status, time = line.split() # this line raises ValueError: the second log line has two fields yield page, int(status), int(time)for page, status, time in requests(read_lines("access.log")): print(page, status, time)/home 200 35 prints before the error. A list-building version would fail before printing anything. A real log parser needs a stage that skips or reports broken lines.
See also: Python Generator Expression vs List, Python yield vs return.
Your turn
read_lines() and requests() are supplied. Write the stage slow(rows), which yields the page of every request that took more than 100 milliseconds. Then print each page from the full pipeline.
/search /report
with open("access.log", "w") as target: target.write("/home 200 35\n/search 200 240\n/about 200 20\n/report 200 900\n")def read_lines(path): with open(path) as file: for line in file: yield line.rstrip("\n")def requests(lines): for line in lines: page, status, time = line.split() yield page, int(status), int(time)# Define slow(rows), then loop over the pipeline and print each page.