From 40229a750e8322074453b761106803de51bbe800 Mon Sep 17 00:00:00 2001 From: Michael Orlitzky Date: Wed, 14 Sep 2022 20:44:09 -0400 Subject: [PATCH] bin/djbdns-logparse: use argparse for arg parse. --- bin/djbdns-logparse | 34 ++++++++++++++++++++++++---------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/bin/djbdns-logparse b/bin/djbdns-logparse index 6cb702f..32c7ba1 100755 --- a/bin/djbdns-logparse +++ b/bin/djbdns-logparse @@ -1,4 +1,8 @@ #!/usr/bin/python3 +""" +Convert tinydns and dnscache logs to human-readable form +""" + # # Reads log files from tinydns and/or dnscache and prints them out in # human-readable form. Logs can be supplied on stdin, or listed on the @@ -25,6 +29,7 @@ from struct import pack from time import strftime, gmtime from subprocess import Popen, PIPE + # common components of line-matching regexes timestamp_pat = r'[\d-]+ [\d:\.]+' # output of tai64nlocal hex4_pat = r'[0-9a-f]{4}' @@ -206,7 +211,7 @@ def handle_tinydns_log(line, match): % (code, ip, port, id, type, name)) -def parse_logfile(file, filename): +def parse_logfile(file): # Open pipe to tai64nlocal: we will write lines of our input (the # raw log file) to it, and read log lines with readable timestamps # from it. @@ -229,15 +234,24 @@ def parse_logfile(file, filename): sys.stdout.write(line) def main(): - if len(sys.argv) > 1: - for filename in sys.argv[1:]: - if filename == "-": - parse_logfile(sys.stdin, "(stdin)") - else: - with open(filename) as file: - parse_logfile(file, filename) - else: - parse_logfile(sys.stdin, "(stdin)") + # Create an argument parser using the file's docsctring as its + # description. + from argparse import ArgumentParser, FileType + parser = ArgumentParser(description = __doc__) + + # Parse zero or more positional arguments into a list of + # "logfiles". If none are given, read from stdin instead. + parser.add_argument("logfiles", + metavar="LOGFILE", + type=FileType("r"), + nargs="*", + default=[sys.stdin], + help="djbdns logfile to process (default: stdin)") + + args = parser.parse_args() + for f in args.logfiles: + parse_logfile(f) + -- 2.44.2