API Reference¶
Complete reference documentation for every public symbol in
errortools. The pages below are generated from the docstrings in
the source tree using sphinx.ext.autodoc; if you spot anything
missing or inaccurate, please open an issue on GitHub.
Contents
Package layout¶
errortools is shipped as a single errortools package that re-exports
the contents of its submodules. The reference below follows the same
layout — every page corresponds to one subpackage or module.
Conventions¶
Every documented object follows the same conventions as the standard library and the pytest API reference:
Type hints use modern PEP 585 syntax (
list[int],type[Exception]) where possible.Docstrings follow the Google style; sections like
Args,Returns,Raises, andExampleare rendered as a structured parameter list.Cross-references use Sphinx roles —
{func}`~errortoolsignore```,PureBaseException``, etc. They resolve to the corresponding entry on this page.
Future module¶
errortools.future¶
Zero-overhead exception handling for hot paths.
Future-focused lightweight exception handling utilities.
Logging¶
errortools.logging¶
A Loguru-inspired structured logger with no external dependencies.
Logging for errortools — loguru-inspired structured logger.
Quick start:
from errortools.logging import logger
logger.info("Hello, {}!", "world")
logger.warning("Disk at {pct}%", pct=90)
# Add a file sink
logger.add("app.log", rotation=10_000_000, retention=5)
# Bind context
req_log = logger.bind(request_id="abc-123")
req_log.debug("Request received")
# Catch exceptions
with logger.catch():
int("oops")
- class errortools.logging.BaseLogger(name='errortools', extra=None)[source]¶
Bases:
objectA loguru-inspired logger with structured sinks, level filtering, and context binding.
Key features¶
Leveled methods:
trace,debug,info,success,warning,error,criticalSink management: add/remove multiple typed sinks via
add/remove(stream, file, or any callable)Context binding: create child loggers with extra fields via
bind— original logger is untouchedException capture: pass
exception=True(or useexception) to attach the current traceback to any recordLevel control: change the minimum level at runtime via
set_level
Usage:
from errortools.logging import logger logger.info("Server started on port {}", 8080) logger.warning("Disk usage at {pct:.1f}%", pct=92.5) with logger.catch(): risky_operation() db_log = logger.bind(db="postgres", user="admin") db_log.debug("Query executed in {ms}ms", ms=42)
- add(sink, *, level=Level.DEBUG, colorize=None, rotation=0, retention=0, encoding='utf-8', fmt=None)[source]¶
Register a new sink and return its integer handle.
- Parameters:
sink (IO[str] | str | Callable[[str], None] | BaseSink) –
Destination — one of:
A writable text stream (
sys.stderr,sys.stdout, …)A file path string or
pathlib.PathA callable
(message: str) -> NoneA
sink.BaseSinkinstance
level (str | int | Level) – Minimum log level for this sink. Accepts a
level.Level, a level name string, or a numeric value.colorize (bool | None) – Force colour on/off for stream sinks.
Noneauto-detects TTY.rotation (int) – Byte threshold for file rotation (file sinks only).
retention (int) – Number of rotated files to keep (file sinks only).
encoding (str) – File encoding (file sinks only).
fmt (str | None) – Custom format string.
- Returns:
An integer sink ID that can be passed to
remove.- Return type:
int
- remove(sink_id=None)[source]¶
Remove a sink by its ID, or remove all sinks if
sink_idisNone.- Parameters:
sink_id (int | None) – Handle returned by
add. PassNoneto clear all.- Return type:
None
- set_level(level)[source]¶
Set the global minimum level for this logger.
Individual sinks can still have their own, stricter filters.
- Parameters:
level (str | int | Level) – Level name, numeric value, or
level.Level.- Return type:
None
- bind(**kwargs)[source]¶
Return a new logger that carries extra context fields.
The original logger is unmodified. Bound fields appear in
record.extraand can be accessed in custom format strings.Example:
req_log = logger.bind(request_id="abc-123") req_log.info("Received request") # record.extra["request_id"] == "abc-123"
- Parameters:
kwargs (Any)
- Return type:
- log(level, message, *args, exception=False, depth=1, **kwargs)[source]¶
Emit a log record at an arbitrary level.
- Parameters:
level (str | int | Level) – Level name, numeric value, or
level.Level.message (str) – Message template. Supports
str.format-style positional ({}) and keyword ({key}) placeholders.*args (Any) – Positional arguments for the message template.
exception (bool) – Capture the current exception info (like loguru’s
opt(exception=True)).depth (int) – Stack depth offset for caller location detection.
**kwargs (Any) – Keyword arguments for the message template.
- Return type:
None
- trace(message, *args, **kwargs)[source]¶
Log at TRACE level (numeric 5).
- Parameters:
message (str)
args (Any)
kwargs (Any)
- Return type:
None
- debug(message, *args, **kwargs)[source]¶
Log at DEBUG level (numeric 10).
- Parameters:
message (str)
args (Any)
kwargs (Any)
- Return type:
None
- info(message, *args, **kwargs)[source]¶
Log at INFO level (numeric 20).
- Parameters:
message (str)
args (Any)
kwargs (Any)
- Return type:
None
- success(message, *args, **kwargs)[source]¶
Log at SUCCESS level (numeric 25).
- Parameters:
message (str)
args (Any)
kwargs (Any)
- Return type:
None
- warning(message, *args, **kwargs)[source]¶
Log at WARNING level (numeric 30).
- Parameters:
message (str)
args (Any)
kwargs (Any)
- Return type:
None
- error(message, *args, **kwargs)[source]¶
Log at ERROR level (numeric 40).
- Parameters:
message (str)
args (Any)
kwargs (Any)
- Return type:
None
- critical(message, *args, **kwargs)[source]¶
Log at CRITICAL level (numeric 50).
- Parameters:
message (str)
args (Any)
kwargs (Any)
- Return type:
None
- exception(message, *args, **kwargs)[source]¶
Log at ERROR level and attach the current exception traceback.
Equivalent to
logger.error(message, exception=True).Example:
try: 1 / 0 except ZeroDivisionError: logger.exception("Math went wrong")
- Parameters:
message (str)
args (Any)
kwargs (Any)
- Return type:
None
- catch(*exceptions, level=Level.ERROR, reraise=False, message="An error has been caught in function '{}', process '{}', thread '{}'")[source]¶
Context manager / decorator that logs uncaught exceptions.
Similar to loguru’s
logger.catch().- Parameters:
*exceptions (type[BaseException]) – Exception types to catch. Defaults to
Exception.level (str | int | Level) – Log level to use when logging the exception.
reraise (bool) – If
True, re-raise after logging.message (str) – Message template — receives
(function, process_id, thread_name).
- Return type:
_CatchContext
Example:
with logger.catch(): int("not a number") @logger.catch(reraise=True) def risky(): ...
- opt(*, exception=False, depth=0, lazy=False)[source]¶
Return a temporary wrapper with extra options.
- Parameters:
exception (bool) – Capture current exception info for the next log call.
depth (int) – Additional stack depth offset for caller location.
lazy (bool) – Ignored (reserved for future lazy-evaluation support).
- Return type:
_OptLogger
Example:
logger.opt(exception=True).error("Something went wrong")
- Parameters:
name (str)
extra (Union[dict[str, Any], None])
- class errortools.logging.Level(name, no, color, icon)[source]¶
Bases:
objectRepresents a single log level with a name, numeric value, and ANSI color.
- Parameters:
name (str)
no (int)
color (str)
icon (str)
- name: str¶
- no: int¶
- color: str¶
- icon: str¶
- errortools.logging.get_level(name_or_no)[source]¶
Return a
Levelby name (case-insensitive) or numeric value.- Raises:
KeyError – If the level is not found.
- Parameters:
name_or_no (str | int)
- Return type:
- class errortools.logging.Record(time, level, message, name, file, line, function, thread_id, thread_name, process_id, exception, extra=<factory>)[source]¶
Bases:
objectImmutable snapshot of a single log event.
Mirrors loguru’s record dict but as a typed dataclass.
- Variables:
time (datetime.datetime) – UTC timestamp when the record was created.
level (_errortools.logging.level.Level) – The
logging.level.Levelof this event.message (str) – The formatted log message (after
str.format/ f-string).name (str) – Logger name (set by the caller or auto-detected).
file (str) – Source file name (
__file__).line (int) – Source line number.
function (str) – Calling function name.
thread_id (int) – OS thread identifier.
thread_name (str) – Thread name.
process_id (int) – OS process id.
exception (tuple[type[BaseException], BaseException, types.TracebackType | None] | None) – The active exception info tuple, or
None.extra (dict[str, Any]) – Arbitrary key/value context bound via
logger.bind().
- Parameters:
time (datetime)
level (Level)
message (str)
name (str)
file (str)
line (int)
function (str)
thread_id (int)
thread_name (str)
process_id (int)
exception (tuple[type[BaseException], BaseException, TracebackType | None] | None)
extra (dict[str, Any])
- time: datetime¶
- message: str¶
- name: str¶
- file: str¶
- line: int¶
- function: str¶
- thread_id: int¶
- thread_name: str¶
- process_id: int¶
- exception: tuple[type[BaseException], BaseException, TracebackType | None] | None¶
- extra: dict[str, Any]¶
- property exc_text: str | None¶
Formatted traceback string, or
Noneif no exception.
- class errortools.logging.BaseSink[source]¶
Bases:
ABCAbstract base class for log sinks.
- class errortools.logging.StreamSink(stream=None, level=Level.DEBUG, colorize=None, fmt=None)[source]¶
Bases:
BaseSinkWrite colourised log lines to a text stream (default:
sys.stderr).- Parameters:
stream (Union[IO[str], None]) – Writable text stream. Defaults to
sys.stderr.level (Level) – Minimum level to emit. Defaults to
Level.DEBUG.colorize (Union[bool, None]) – Force colour on/off.
None(default) auto-detects TTY.fmt (Union[str, None]) – Custom format string.
Noneuses the default format.diagnose – Include exception variable values in tracebacks (future).
- class errortools.logging.FileSink(path, level=Level.DEBUG, rotation=0, retention=0, encoding='utf-8', fmt=None)[source]¶
Bases:
BaseSinkWrite plain-text log lines to a file, with optional size-based rotation.
- Parameters:
path (Union[str, Path]) – Path to the log file. Parent directories are created.
level (Level) – Minimum level to emit. Defaults to
Level.DEBUG.rotation (int) – Maximum file size in bytes before rotation.
0= no rotation.retention (int) – Number of rotated files to keep (oldest are deleted).
0= keep all.encoding (str) – File encoding. Defaults to
"utf-8".fmt (Union[str, None]) – Custom format string.
Noneuses the default format.
Type aliases¶
- errortools.ExceptionType¶
type(object) -> the object’s type type(name, bases, dict, **kwds) -> a new type
alias of
type[Exception]
- errortools.WarningType¶
type(object) -> the object’s type type(name, bases, dict, **kwds) -> a new type
alias of
type[Warning]
- errortools.AnyErrorCode¶
alias of
InvalidInputError|AccessDeniedError|NotFoundError|RuntimeFailure|TimeoutFailure|ConfigurationError
Version utilities¶
Lightweight helpers for representing, parsing, and comparing the
package’s own (major, minor, patch) version triple programmatically.
VersionInfo— a hashable, totally-ordered dataclass for an individual version triple.get_version_tuple()— parse a dotted-decimal version string into a(major, minor, patch)tuple.