|
| 1 | +# SPDX-License-Identifier: GPL-3.0-only |
| 2 | +# |
| 3 | +# This program is free software: you can redistribute it and/or modify |
| 4 | +# it under the terms of the GNU General Public License as published by |
| 5 | +# the Free Software Foundation, version 3 of the License. |
| 6 | +# |
| 7 | +# This program is distributed in the hope that it will be useful, |
| 8 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 9 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 10 | +# GNU General Public License for more details. |
| 11 | +# |
| 12 | +# You should have received a copy of the GNU General Public License |
| 13 | +# along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 14 | +# |
| 15 | +# Copyright (c) 2024, YeetCode Developers <[email protected]> |
| 16 | + |
| 17 | +import logging |
| 18 | +import os |
| 19 | + |
| 20 | +GLOBAL_DEBUG: bool = False |
| 21 | +if os.getenv("TGBOT_DEBUG") is not None: |
| 22 | + GLOBAL_DEBUG = True |
| 23 | + |
| 24 | +log_additional_args: dict = {"filename": "bot.log", "level": logging.INFO} |
| 25 | +if GLOBAL_DEBUG: |
| 26 | + log_additional_args.clear() |
| 27 | + log_additional_args.update({"level": logging.DEBUG}) |
| 28 | + |
| 29 | + |
| 30 | +# |
| 31 | +# Adapted from https://stackoverflow.com/a/56944256 |
| 32 | +# |
| 33 | +class ColouredFormatter(logging.Formatter): |
| 34 | + |
| 35 | + grey = "\x1b[38;20m" |
| 36 | + yellow = "\x1b[33;20m" |
| 37 | + red = "\x1b[31;20m" |
| 38 | + green = "\x1b[0;32m" |
| 39 | + blue = "\x1b[0;34m" |
| 40 | + bold_red = "\x1b[31;1m" |
| 41 | + reset = "\x1b[0m" |
| 42 | + format_str = "%(asctime)s [%(levelname)s] %(name)s: %(message)s" |
| 43 | + |
| 44 | + FORMATS = { |
| 45 | + logging.DEBUG: blue + format_str + reset, |
| 46 | + logging.INFO: green + format_str + reset, |
| 47 | + logging.WARNING: yellow + format_str + reset, |
| 48 | + logging.ERROR: red + format_str + reset, |
| 49 | + logging.CRITICAL: bold_red + format_str + reset, |
| 50 | + } |
| 51 | + |
| 52 | + def format(self, record: logging.LogRecord): |
| 53 | + log_fmt = self.FORMATS.get(record.levelno) |
| 54 | + formatter = logging.Formatter(log_fmt) |
| 55 | + return formatter.format(record) |
| 56 | + |
| 57 | + |
| 58 | +logging.basicConfig(format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", **log_additional_args) |
| 59 | + |
| 60 | + |
| 61 | +for handler in logging.root.handlers: |
| 62 | + if issubclass(logging.StreamHandler, type(handler)): |
| 63 | + logging.root.removeHandler(handler) |
| 64 | + |
| 65 | +_sh = logging.StreamHandler() |
| 66 | +_sh.setFormatter(ColouredFormatter()) |
| 67 | +logging.root.addHandler(_sh) |
| 68 | +logging.getLogger(__name__).info("Coloured log output initialized") |
0 commit comments