From f25211451281423e478270867596dc2a34515c0a Mon Sep 17 00:00:00 2001 From: Michael Orlitzky Date: Thu, 15 Sep 2022 18:50:26 -0400 Subject: [PATCH] bin/djbdns-logparse.py: move regex handling down a level. It was a bit awkward to match a line against a regex, and then to have to immediately pass that match object into a function that knows what to do with it (to avoid duplicating work). Now the handle_tinydns_log() and handle_dnscache_log() functions create the match object themselves, and signal success or failure by returning a boolean. --- bin/djbdns-logparse.py | 43 ++++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/bin/djbdns-logparse.py b/bin/djbdns-logparse.py index 689e33b..33fc69d 100755 --- a/bin/djbdns-logparse.py +++ b/bin/djbdns-logparse.py @@ -128,7 +128,11 @@ def decode_type(words, i): qt = words[i] words[i] = query_type.get(int(qt), qt) -def handle_dnscache_log(line, match): +def handle_dnscache_log(line) -> bool: + match = dnscache_log_re.match(line) + if not match: + return False + (timestamp, event, data) = match.groups() words = data.split() @@ -198,31 +202,37 @@ def handle_dnscache_log(line, match): decode_client(words, 0) print(timestamp, event, " ".join(words)) + return True -def handle_tinydns_log(line : str, match: re.Match): +def handle_tinydns_log(line : str) -> bool: """ - Handle a line that matched the ``tinydns_log_re`` regex. + Handle a single log line if it matches the ``tinydns_log_re`` regex. Parameters ---------- line : string - The tinydns log line that matched ``tinydns_log_re``. + The log line that might match ``tinydns_log_re``. + + Returns + ------- - match : re.Match - The match object that was returned when ``line`` was - tested against ``tinydns_log_re``. + ``True`` if the log line was handled (that is, if it was really a + tinydns log line), and ``False`` otherwise. Examples -------- >>> line = "2022-09-14 21:04:40.206516500 7f000001:9d61:be69 - 0001 www.example.com" - >>> match = tinydns_log_re.match(line) - >>> handle_tinydns_log(line, match) + >>> _ = handle_tinydns_log(line) 2022-09-14 21:04:40.206516500 dropped query (no authority) from 127.0.0.1:40289 (id 48745): a www.example.com """ + match = tinydns_log_re.match(line) + if not match: + return False + (timestamp, ip, port, id, code, type, name) = match.groups() ip = convert_ip(ip) port = int(port, 16) @@ -252,6 +262,7 @@ def handle_tinydns_log(line : str, match: re.Match): id=id, type=type, name=name)) + return True def parse_logfile(file : typing.TextIO): @@ -288,17 +299,9 @@ def parse_logfile(file : typing.TextIO): tai.stdin.write(line) line = tai.stdout.readline() - match = tinydns_log_re.match(line) - if match: - handle_tinydns_log(line, match) - continue - - match = dnscache_log_re.match(line) - if match: - handle_dnscache_log(line, match) - continue - - print(line) + if not handle_tinydns_log(line): + if not handle_dnscache_log(line): + print(line, end='') def main(): r""" -- 2.43.2