Error Handling and Formatting Utilities¶
Overview¶
This module primarily provides javaishstacktrace() and a custom version of
warnings.showwarning(), both of which produce somewhat shorter messages than the default Python messages.
They can be set up via the context manager CustomHandlers or, more typically, via a
call to init_handlers() at the beginning of the script.
This module also provides logging_config() for configuration of logging.
Functions¶
- igbpyutils.error.running_in_unittest() bool[source]¶
Attempt to detect if we’re running under
unittest.This is slightly hackish and used in this module only for slightly nicer output during testing.
- igbpyutils.error.extype_fullname(ex: type) str[source]¶
Return the name of an exception together with its module name, if any.
- igbpyutils.error.ex_repr(ex: BaseException) str[source]¶
Return a representation of the exception including its full name and
.args.
- igbpyutils.error.asyncio_exception_handler(loop, ctx: dict[str, Any])¶
A custom version of
asyncio’sloop.set_exception_handler().
- class igbpyutils.error.CustomHandlers(*, repeat_msg: bool = False)[source]¶
A context manager that installs and removes this module’s custom error and warning handlers.
This modifies
warnings.showwarning(),sys.excepthook(),sys.unraisablehook(),threading.excepthook(), and, if there’s a runningasyncioevent loop, sets itsloop.set_exception_handler()toasyncio_exception_handler(). The latter can also be done manually later if there is no running loop at the moment.- Parameters:
repeat_msg – See the corresponding argument of
javaishstacktrace().
- igbpyutils.error.init_handlers(*, repeat_msg: bool = False) None[source]¶
Set up the
CustomHandlersonce and don’t change them back.- Parameters:
repeat_msg – See the corresponding argument of
javaishstacktrace().
- igbpyutils.error.javaishstacktrace(ex: BaseException, *, repeat_msg: bool = False) Generator[str, None, None][source]¶
Generate a stack trace in the style of Java.
Compared to Java, the order of exceptions is reversed, so it reads more like a stack.
Can be used like so:
"\n".join(javaishstacktrace(ex))AssertionErroris treated specially in that the line of source code that caused them is printed.- Parameters:
repeat_msg – If this is true, then the exception type and message are repeated at the bottom of the stack trace, without escaping of the message. This is intended to make the exception message easier for a user to read. Default is false.
- class igbpyutils.error.CustomFormatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)[source]¶
This is a custom
logging.Formatterthat logs errors usingjavaishstacktrace().It also has some better defaults for
asctimeformatting (mostly that it is GMT and output with aZsuffix).- Seealso:
- converter()¶
- gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,
tm_sec, tm_wday, tm_yday, tm_isdst)
Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a. GMT). When ‘seconds’ is not passed in, convert the current time instead.
If the platform supports the tm_gmtoff and tm_zone, they are available as attributes only.
- default_time_format = '%Y-%m-%d %H:%M:%S'¶
- default_msec_format = '%s.%03dZ'¶
- class igbpyutils.error.LoggingStream(*args, **kwargs)[source]¶
The minimum required interface of a stream for
logging.StreamHandler, according to its documentation.
- igbpyutils.error.logging_config(*, level: int = 30, stream: None | Literal[True] | LoggingStream = None, filename: str | PathLike | None = None, fmt: str | None = '[%(asctime)s] %(levelname)s %(name)s: %(message)s')[source]¶
A replacement for
logging.basicConfig()that usesCustomFormatterand has a few more useful defaults.- Parameters:
level – Set the root logger level to the specified level. Defaults to
logging.WARNING.stream – Use the specified stream to initialize the
StreamHandler. Can also beTrueto specify thatsys.stderrshould be used (which is the default anyway, except when a filename is specified).filename – Specifies that a
FileHandlerbe created using the specified filename.fmt – Use the specified format string for the handler(s).
Other defaults are: Files are always encoded with UTF-8, and any existing handlers are always removed.
Note I also recommend using
logging.captureWarnings().