From 693029fd21b83efb46d9708fff6e48b282aada27 Mon Sep 17 00:00:00 2001 From: xeals Date: Mon, 27 Mar 2023 23:07:10 +1100 Subject: [PATCH] make logger not bad --- main.py | 37 ++++++++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/main.py b/main.py index bb65cbc..06d7182 100755 --- a/main.py +++ b/main.py @@ -12,15 +12,28 @@ import sys import typing as t +class LogFormatter(logging.Formatter): + + format = "%(name)s [%(levelname)s] %(message)s" + FORMATS = { + logging.DEBUG: f"\x1b[38;20m{format}\x1b[0m", + logging.INFO: f"\x1b[34;20m{format}\x1b[0m", + logging.WARNING: f"\x1b[33;20m{format}\x1b[0m", + logging.ERROR: f"\x1b[31;20m{format}\x1b[0m", + logging.CRITICAL: f"\x1b[31;1m{format}\x1b[0m", + } + + def format(self, record): + fmt = self.FORMATS.get(record.levelno) + formatter = logging.Formatter(fmt) + return formatter.format(record) + + APP = "hhirlstats" - - -def error(*args, **kwargs): - logging.getLogger(APP).error(*args, **kwargs) - - -def debug(*args, **kwargs): - logging.getLogger(APP).debug(*args, **kwargs) +LOG = logging.getLogger(APP) +_ch = logging.StreamHandler() +_ch.setFormatter(LogFormatter()) +LOG.addHandler(_ch) class safelist(list): @@ -125,7 +138,8 @@ def parse_log(game: str, log: str, into: sqlite3.Connection): (game, turn, player, mon), ) case _: - debug(f"unhandled message {chunks[0]}") + # LOG.debug(f"unhandled message {chunks[0]}") + pass @dataclass(frozen=True) @@ -177,7 +191,7 @@ def main(): parser.add_argument("replay", nargs="+", help="replay ID or URL") args = parser.parse_args(sys.argv[1:]) - logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO) + LOG.setLevel(logging.DEBUG if args.verbose else logging.INFO) try: db = sqlite3.connect("data.db") @@ -187,9 +201,10 @@ def main(): try: replay = fetch(r, cache=args.cache) except Exception as e: - error(f"bad replay {r}") + LOG.error(f"bad replay {r}") continue + LOG.info(f"indexing game {replay.id}") db.execute( """ INSERT INTO games(id, p1, p2, format, uploadtime)