Parsing Log Files¶
Logs are not only for reading with your eyes. Sometimes you want to analyze them: find the slow requests of the last hour, count errors per user, extract the data for a report...
Logust includes two small helpers to read log files back as Python dicts: parse() for text logs, and parse_json() for JSON logs.
Parse a text log¶
parse() takes a file path and a regular expression with named groups. It reads the file line by line, and gives you a dict with the groups of each line that matches:
from logust import logger, parse
logger.remove()
logger.add("app.log", format="{time} | {level:<8} | {message}", mode="w")
logger.info("Server started")
logger.warning("Disk usage is at 91%")
logger.error("Payment failed")
logger.complete()
pattern = r"(?P<time>[\d-]+ [\d:.]+) \| (?P<level>\w+)\s+\| (?P<message>.*)"
for record in parse("app.log", pattern):
print(record)
Each named group, like (?P<level>\w+), becomes a key of the dict.
A few details:
- Lines that don't match the pattern are skipped. That's convenient for multi-line messages like tracebacks: only the first line of each record matches.
- The pattern must match from the start of the line (it's used with
re.match()). parse()is a generator: it reads the file lazily, so it works with big files too.- The file is read as UTF-8, invalid bytes are replaced.
Tip
Write the pattern for the format you used in logger.add(). If you control both, a simple and regular format (like {time} | {level:<8} | {message}) makes the pattern easy.
Convert values with cast¶
All the values are strings by default. Pass cast to convert some groups, with a dict of group name to type (or any function that takes a string):
from logust import logger
logger.remove()
logger.add("requests.log", format="{level} {extra[path]} {extra[status]} {extra[ms]}ms", mode="w")
logger.info("Request", path="/", status=200, ms=12)
logger.info("Request", path="/search", status=200, ms=840)
logger.info("Request", path="/cart", status=500, ms=33)
logger.complete()
pattern = r"(?P<level>\w+) (?P<path>\S+) (?P<status>\d+) (?P<ms>\d+)ms"
slow = [
record
for record in logger.parse("requests.log", pattern, cast={"status": int, "ms": int})
if record["ms"] > 500
]
print(slow)
status and ms are ints now, so record["ms"] > 500 works. 🎉
If a conversion fails (a ValueError or TypeError), the value is kept as a string.
Notice that this example uses logger.parse(): it's the same function as logust.parse(), available on the logger like in loguru.
Technical Details
Unlike loguru's logger.parse(), Logust's takes a file path (not an open file), and cast must be a dict. parse() also accepts a chunk_size= argument, which currently has no effect.
Parse a JSON log¶
If you write your logs with serialize=True, there's no need for a pattern. parse_json() reads a JSON Lines file, one JSON object per line:
from logust import logger, parse_json
logger.remove()
logger.add("app.json", serialize=True, mode="w")
logger.bind(user="alice").info("Logged in")
logger.bind(user="bob").error("Payment failed")
logger.complete()
for record in parse_json("app.json"):
print(record["level"], record["message"], record["extra"])
errors = [r for r in parse_json("app.json") if r["level"] == "ERROR"]
print(len(errors), "error(s)")
Each record is the dict that was serialized, with time, level, message, the caller fields, and extra.
By default, lines that are not valid JSON are skipped, and empty lines too. Pass strict=True to raise a ValueError on the first invalid line instead, with its line number:
Recap¶
parse(path, pattern)yields a dict of the named groups of each matching line.cast={"ms": int}converts values.logger.parse()is the same aslogust.parse().parse_json(path)reads JSON Lines files written withserialize=True.- Both are generators, so they work with large files.