|
| 1 | +# log21.CrashReporter.Formatters.py |
| 2 | +# CodeWriter21 |
| 3 | + |
| 4 | +import traceback |
| 5 | + |
| 6 | +from datetime import datetime as _datetime |
| 7 | + |
| 8 | +__all__ = ['Formatter', 'CONSOLE_REPORTER_FORMAT', 'FILE_REPORTER_FORMAT', 'EMAIL_REPORTER_FORMAT'] |
| 9 | + |
| 10 | + |
| 11 | +class Formatter: |
| 12 | + def __init__(self, format_: str, style: str = '%', datefmt: str = '%Y-%m-%d %H:%M:%S'): |
| 13 | + self._format = format_ |
| 14 | + |
| 15 | + if style in ['%', '{']: |
| 16 | + self.__style = style |
| 17 | + else: |
| 18 | + raise ValueError('Invalid style: "' + str(style) + '" Valid styles: %, {') |
| 19 | + |
| 20 | + self.datefmt = datefmt |
| 21 | + |
| 22 | + def format(self, exception: Exception): |
| 23 | + exception_dict = { |
| 24 | + '__name__': __name__, |
| 25 | + 'type': type(exception), |
| 26 | + 'message': exception.args[0], |
| 27 | + 'traceback': traceback.format_tb(exception.__traceback__.tb_next), |
| 28 | + 'name': exception.__class__.__name__, |
| 29 | + 'file': exception.__traceback__.tb_next.tb_frame.f_code.co_filename, |
| 30 | + 'lineno': exception.__traceback__.tb_next.tb_lineno, |
| 31 | + 'function': exception.__traceback__.tb_next.tb_frame.f_code.co_name, |
| 32 | + 'asctime': _datetime.now().strftime(self.datefmt), |
| 33 | + } |
| 34 | + |
| 35 | + if self.__style == '%': |
| 36 | + return self._format % exception_dict |
| 37 | + elif self.__style == '{': |
| 38 | + return self._format.format(**exception_dict) |
| 39 | + else: |
| 40 | + raise ValueError('Invalid style: "' + str(self.__style) + '" Valid styles: %, {') |
| 41 | + |
| 42 | + |
| 43 | +CONSOLE_REPORTER_FORMAT = dict( |
| 44 | + format_=f'\033[91m%(name)s: %(message)s\033[0m\n' # Name and message of the exception. |
| 45 | + f'\tFile\033[91m:\033[0m "%(file)s"\n' # The file that exception was raised in. |
| 46 | + f'\tLine\033[91m:\033[0m %(lineno)d', # The line that exception was raised on. |
| 47 | + style='%' |
| 48 | +) |
| 49 | + |
| 50 | +FILE_REPORTER_FORMAT = dict( |
| 51 | + format_=f'[%(asctime)s] %(name)s: %(message)s' # Name and message of the exception. |
| 52 | + f'; File: "%(file)s"' # The file that exception was raised in. |
| 53 | + f'; Line: %(lineno)d\n', # The line that exception was raised on. |
| 54 | + style='%' |
| 55 | +) |
| 56 | + |
| 57 | +EMAIL_REPORTER_FORMAT = dict( |
| 58 | + format_=""" |
| 59 | + <html> |
| 60 | + <body> |
| 61 | + <h1>Crash Report: %(__name__)s</h1> |
| 62 | + <h2>%(name)s: %(message)s</h2> |
| 63 | + <p> |
| 64 | + <span style="bold">File:</span> "%(file)s"<br> |
| 65 | + <span style="bold">Line:</span> %(lineno)d<br> |
| 66 | + <span style="center">%(asctime)s</span><br> |
| 67 | + </p> |
| 68 | + <body> |
| 69 | + </html> |
| 70 | + """, |
| 71 | + style='%' |
| 72 | +) |
0 commit comments