|
| 1 | +# Copyright (C) 2022 Gradience Team |
| 2 | +# Copyright 2023-2025, tfuxu <https://github.com/tfuxu> |
| 3 | +# Copyright (C) 2025 Alexander Vanhee |
| 4 | +# |
| 5 | +# This program is free software: you can redistribute it and/or modify |
| 6 | +# it under the terms of the GNU General Public License as published by |
| 7 | +# the Free Software Foundation, either version 3 of the License, or |
| 8 | +# (at your option) any later version. |
| 9 | +# |
| 10 | +# This program is distributed in the hope that it will be useful, |
| 11 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | +# GNU General Public License for more details. |
| 14 | +# |
| 15 | +# You should have received a copy of the GNU General Public License |
| 16 | +# along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 17 | +# |
| 18 | +# SPDX-License-Identifier: GPL-3.0-or-later |
| 19 | + |
| 20 | +import sys |
| 21 | +import logging |
| 22 | +import traceback |
| 23 | + |
| 24 | +class Logger(logging.getLoggerClass()): |
| 25 | + """ |
| 26 | + This is a wrapper of `logging` module. It provides |
| 27 | + custom formatting for log messages. |
| 28 | +
|
| 29 | + Attributes |
| 30 | + ---------- |
| 31 | + issue_footer_levels : list, optional |
| 32 | + Custom list of levels on which to show issue footer. |
| 33 | + [Allowed values: warning, error, traceback_error, critical] |
| 34 | + formatter : str, optional |
| 35 | + Custom formatter for the logger. |
| 36 | + """ |
| 37 | + |
| 38 | + log_colors = { |
| 39 | + "debug": 32, |
| 40 | + "info": 36, |
| 41 | + "warning": 33, |
| 42 | + "error": 31, |
| 43 | + "critical": 41 |
| 44 | + } |
| 45 | + |
| 46 | + log_format = { |
| 47 | + 'fmt': '%(message)s' |
| 48 | + } |
| 49 | + |
| 50 | + issue_footer = "If you are reporting an issue, please copy the logs printed above to the issue body." |
| 51 | + |
| 52 | + issue_footer_levels = [ |
| 53 | + "error", |
| 54 | + "traceback_error", |
| 55 | + "critical" |
| 56 | + ] |
| 57 | + |
| 58 | + def __set_traceback_info(self, exception: BaseException | None = None) -> str: |
| 59 | + if not exception: |
| 60 | + exception = sys.exc_info()[1] |
| 61 | + traceback = self.get_traceback(exception) |
| 62 | + |
| 63 | + message_head = "\n\t\033[1mTraceback:\033[0m" |
| 64 | + message_body = f"\n\033[90m{traceback}\033[0m" |
| 65 | + message_body = message_body.replace("\n", "\n\t\t") |
| 66 | + |
| 67 | + return message_head + message_body |
| 68 | + |
| 69 | + def __set_exception_info(self, exception: BaseException | None = None) -> str: |
| 70 | + if not exception: |
| 71 | + exception = sys.exc_info()[1] |
| 72 | + |
| 73 | + message_head = "\n\t\033[1mException:\033[0m" |
| 74 | + message_body = f"\n{exception}" |
| 75 | + message_body = message_body.replace("\n", "\n\t\t") |
| 76 | + |
| 77 | + return message_head + message_body |
| 78 | + |
| 79 | + def __set_level_color(self, level: str, message: str) -> str: |
| 80 | + color_id = self.log_colors[level] |
| 81 | + |
| 82 | + return f"[\033[1;{color_id}m{level.upper()}\033[0m] {message}" |
| 83 | + |
| 84 | + def __init__(self, issue_footer_levels: list | None = None, fmt: str | None = None): |
| 85 | + """ |
| 86 | + The constructor for Logger class. |
| 87 | + """ |
| 88 | + |
| 89 | + super().__init__(name="Gradia") |
| 90 | + |
| 91 | + if issue_footer_levels: |
| 92 | + self.issue_footer_levels = issue_footer_levels |
| 93 | + |
| 94 | + formatter = logging.Formatter(self.log_format["fmt"]) |
| 95 | + if fmt: |
| 96 | + formatter = logging.Formatter(fmt) |
| 97 | + |
| 98 | + self.root.setLevel(logging.DEBUG) |
| 99 | + |
| 100 | + self.root.handlers = [] |
| 101 | + |
| 102 | + handler = logging.StreamHandler() |
| 103 | + handler.setFormatter(formatter) |
| 104 | + self.root.addHandler(handler) |
| 105 | + |
| 106 | + def debug(self, message: str, *args, **kwargs) -> None: |
| 107 | + self.root.debug(self.__set_level_color("debug", str(message))) |
| 108 | + |
| 109 | + def info(self, message: str, *args, **kwargs) -> None: |
| 110 | + self.root.info(self.__set_level_color("info", str(message))) |
| 111 | + |
| 112 | + def warning(self, message: str, exception: BaseException | None = None, |
| 113 | + show_exception: bool = False, show_traceback: bool = False, *args, **kwargs) -> None: |
| 114 | + if show_exception: |
| 115 | + message += self.__set_exception_info(exception) |
| 116 | + if show_traceback: |
| 117 | + message += self.__set_traceback_info(exception) |
| 118 | + |
| 119 | + self.root.warning(self.__set_level_color("warning", str(message))) |
| 120 | + if "warning" in self.issue_footer_levels: |
| 121 | + self.print_issue_footer() |
| 122 | + |
| 123 | + def error(self, message: str, exception: BaseException | None = None, |
| 124 | + show_exception: bool = False, show_traceback: bool = False, *args, **kwargs) -> None: |
| 125 | + if show_exception: |
| 126 | + message += self.__set_exception_info(exception) |
| 127 | + if show_traceback: |
| 128 | + message += self.__set_traceback_info(exception) |
| 129 | + |
| 130 | + self.root.error(self.__set_level_color("error", str(message))) |
| 131 | + if "error" in self.issue_footer_levels: |
| 132 | + self.print_issue_footer() |
| 133 | + |
| 134 | + def traceback_error(self, message: str, exception: BaseException | None = None, |
| 135 | + show_exception: bool = False) -> None: |
| 136 | + if show_exception: |
| 137 | + message += self.__set_exception_info(exception) |
| 138 | + message += self.__set_traceback_info(exception) |
| 139 | + |
| 140 | + self.root.error(self.__set_level_color("error", str(message))) |
| 141 | + if "traceback_error" in self.issue_footer_levels: |
| 142 | + self.print_issue_footer() |
| 143 | + |
| 144 | + def critical(self, message: str, exception: BaseException | None = None, |
| 145 | + show_exception: bool = False, show_traceback: bool = True, *args, **kwargs) -> None: |
| 146 | + if show_exception: |
| 147 | + message += self.__set_exception_info(exception) |
| 148 | + if show_traceback: |
| 149 | + message += self.__set_traceback_info(exception) |
| 150 | + |
| 151 | + self.root.critical(self.__set_level_color("critical", str(message))) |
| 152 | + if "critical" in self.issue_footer_levels: |
| 153 | + self.print_issue_footer() |
| 154 | + |
| 155 | + def set_silent(self) -> None: |
| 156 | + self.root.handlers = [] |
| 157 | + |
| 158 | + def print_issue_footer(self) -> None: |
| 159 | + self.root.info(self.__set_level_color("info", self.issue_footer)) |
| 160 | + |
| 161 | + def get_traceback(self, exception: BaseException | None) -> str | None: |
| 162 | + if not exception: |
| 163 | + return |
| 164 | + |
| 165 | + traceback_list = traceback.format_exception(exception) |
| 166 | + exception_tb = "".join(traceback_list) |
| 167 | + |
| 168 | + return exception_tb |
| 169 | + |
| 170 | + |
| 171 | +""" |
| 172 | +Use for testing only. |
| 173 | +How to execute: python -m gradia.backend.logger |
| 174 | +""" |
| 175 | +# pylint: disable=W0719,W0718,W0707 |
| 176 | +if __name__ == "__main__": |
| 177 | + logging = Logger() |
| 178 | + |
| 179 | + logging.info("This is an information.") |
| 180 | + logging.debug("This is a debug message.") |
| 181 | + |
| 182 | + try: |
| 183 | + raise ArithmeticError("Arithmetic Error") |
| 184 | + except Exception: |
| 185 | + try: |
| 186 | + raise Exception("General Exception") |
| 187 | + except Exception as e: |
| 188 | + logging.traceback_error("This is an test error.", exception=e, show_exception=True) |
| 189 | + |
| 190 | + print(f"Retrieved traceback: {logging.get_traceback(e)}") |
0 commit comments