Diagnostics Module¶
The rite.diagnostics module provides logging, profiling, error handling, and debugging utilities.
Overview¶
diagnostics ¶
Diagnostics Module¶
Comprehensive diagnostics and monitoring utilities.
This module provides utilities for logging, error handling, profiling, debugging, and metrics collection.
Submodules¶
- logging: Structured logging, file/console output, contextual logging
- errors: Exception handling, retry logic, traceback formatting
- profiling: Timing, memory profiling, call counting
- debugging: Object inspection, function tracing, state dumping
- metrics: Counters, gauges, histograms, timers
Examples¶
Logging: >>> from rite.diagnostics import logging_structured >>> logging_structured("INFO", "Application started", user="admin")
Error Handling
from rite.diagnostics import errors_retry @errors_retry(max_attempts=3) ... def api_call(): ... pass
Profiling
from rite.diagnostics import profiling_timer @profiling_timer() ... def slow_function(): ... pass
Debugging
from rite.diagnostics import debugging_trace @debugging_trace() ... def calculate(x, y): ... return x + y
Metrics
from rite.diagnostics import metrics_counter counter = metrics_counter("requests") counter.increment()
Classes¶
ErrorHandler ¶
Error Handler Class¶
A class to handle and log errors in the system. It provides methods for logging errors, raising alerts, and retrying operations.
Attributes¶
log_file : str | None The path to the log file for error logging.
Initializes the ErrorHandler with a specified log file.
Parameters:¶
log_file : str | None The path to the log file (default: 'error_log.txt').
Functions¶
log_error ¶
raise_alert ¶
Raises an alert for critical errors and logs the alert message.
Parameters:¶
error : str The error message to alert on.
retry_operation ¶
Retries a specified operation a given number of times with optional exponential backoff.
Parameters:¶
operation : Callable The operation (function) to retry. retries : int, optional The number of retry attempts (default: 3). backoff : float, optional The initial backoff time in seconds between retries (default: 1.0).
Returns¶
bool: True if the operation succeeded, False if all retries failed.
Logger ¶
Logger Class¶
A configurable logger that supports logging to both console and file outputs with various log levels. This class wraps Python's built-in logging module, providing an easy interface to integrate logging into applications.
Attributes¶
logger : logging.Logger The underlying logger instance from Python's logging module. log_file : str | None Path to the log file if file logging is enabled.
Initializes a new Logger instance with the specified name and optional log file.
Parameters:¶
name : str The name of the logger, typically the module or application name. log_file : str | None Path to a log file for file logging. If None, logging to file is disabled.
Example:¶
logger = Logger(name="MyApp", log_file="app.log") logger.info("Application started")
Modules¶
debugging ¶
Debugging Module¶
Debugging and inspection utilities.
This submodule provides utilities for inspecting objects, tracing function calls, and dumping variable states.
Examples¶
from rite.diagnostics.debugging import ( ... debugging_inspect, ... debugging_trace, ... debugging_dump ... ) @debugging_trace() ... def example(): ... pass
Modules¶
debugging_dump ¶
State Dumper¶
Dump variable states for debugging.
Examples¶
from rite.diagnostics.debugging import debugging_dump debugging_dump(x=1, y=2, name="test")
debugging_inspect ¶
Variable Inspector¶
Inspect variables and their attributes.
Examples¶
from rite.diagnostics.debugging import debugging_inspect obj = {"key": "value"} debugging_inspect(obj)
Inspect object attributes and methods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
Object to inspect. |
required |
show_private
|
bool
|
Include private attributes (starting with _). |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with object information. |
Examples:
debugging_locals ¶
Locals Dumper¶
Dump all local variables in current scope.
Examples¶
from rite.diagnostics.debugging import debugging_locals def example(): ... x = 1 ... y = 2 ... debugging_locals()
Dump local variables from calling scope.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
show_private
|
bool
|
Include private variables (starting with _). |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary of local variables. |
Examples:
>>> def test():
... x = 42
... y = "hello"
... locals_dict = debugging_locals()
... return "x" in locals_dict
>>> test()
True
Notes
This function inspects the caller's frame to get locals.
debugging_trace ¶
Function Tracer¶
Trace function calls with arguments and returns.
Examples¶
from rite.diagnostics.debugging import debugging_trace @debugging_trace() ... def add(a, b): ... return a + b
debugging_trace(show_args: bool = True, show_return: bool = True) -> Callable[[Callable[..., T]], Callable[..., T]]
Decorator to trace function calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
show_args
|
bool
|
Show function arguments. |
True
|
show_return
|
bool
|
Show return value. |
True
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., T]], Callable[..., T]]
|
Decorated function with tracing. |
Examples:
debugging_dump ¶
State Dumper¶
Dump variable states for debugging.
Examples¶
from rite.diagnostics.debugging import debugging_dump debugging_dump(x=1, y=2, name="test")
debugging_inspect ¶
Variable Inspector¶
Inspect variables and their attributes.
Examples¶
from rite.diagnostics.debugging import debugging_inspect obj = {"key": "value"} debugging_inspect(obj)
Functions¶
debugging_inspect ¶
Inspect object attributes and methods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
Object to inspect. |
required |
show_private
|
bool
|
Include private attributes (starting with _). |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with object information. |
Examples:
debugging_locals ¶
Locals Dumper¶
Dump all local variables in current scope.
Examples¶
from rite.diagnostics.debugging import debugging_locals def example(): ... x = 1 ... y = 2 ... debugging_locals()
Functions¶
debugging_locals ¶
Dump local variables from calling scope.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
show_private
|
bool
|
Include private variables (starting with _). |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary of local variables. |
Examples:
>>> def test():
... x = 42
... y = "hello"
... locals_dict = debugging_locals()
... return "x" in locals_dict
>>> test()
True
Notes
This function inspects the caller's frame to get locals.
debugging_trace ¶
Function Tracer¶
Trace function calls with arguments and returns.
Examples¶
from rite.diagnostics.debugging import debugging_trace @debugging_trace() ... def add(a, b): ... return a + b
Functions¶
debugging_trace ¶
debugging_trace(show_args: bool = True, show_return: bool = True) -> Callable[[Callable[..., T]], Callable[..., T]]
Decorator to trace function calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
show_args
|
bool
|
Show function arguments. |
True
|
show_return
|
bool
|
Show return value. |
True
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., T]], Callable[..., T]]
|
Decorated function with tracing. |
Examples:
error_handler ¶
Error Handling Module¶
This module provides the ErrorHandler class for managing and logging errors
in the system. It supports error logging, raising alerts, and retrying failed
operations with customizable retry logic.
Classes:¶
- ErrorHandler: Handles error logging, alerting, and retrying operations.
Features:¶
- Logs errors to a specified log file.
- Raises alerts for critical errors.
- Retries failed operations with configurable retry limits and exponential backoff.
Classes¶
ErrorHandler ¶
Error Handler Class¶
A class to handle and log errors in the system. It provides methods for logging errors, raising alerts, and retrying operations.
Attributes¶
log_file : str | None The path to the log file for error logging.
Initializes the ErrorHandler with a specified log file.
Parameters:¶
log_file : str | None The path to the log file (default: 'error_log.txt').
Raises an alert for critical errors and logs the alert message.
Parameters:¶
error : str The error message to alert on.
Retries a specified operation a given number of times with optional exponential backoff.
Parameters:¶
operation : Callable The operation (function) to retry. retries : int, optional The number of retry attempts (default: 3). backoff : float, optional The initial backoff time in seconds between retries (default: 1.0).
Returns¶
bool: True if the operation succeeded, False if all retries failed.
Functions¶
errors ¶
Error Handling Module¶
Error handling utilities with retry, catching, and formatting.
This submodule provides utilities for handling errors gracefully: retry decorators, exception context managers, traceback formatting, and exception chain analysis.
Examples¶
from rite.diagnostics.errors import errors_retry, errors_catch @errors_retry(max_attempts=3) ... def flaky_function(): ... pass with errors_catch(): ... risky_operation()
Modules¶
errors_catch ¶
Exception Context Manager¶
Context manager to catch and handle exceptions gracefully.
Examples¶
from rite.diagnostics.errors import errors_catch with errors_catch(): ... risky_operation()
errors_catch(exceptions: tuple[type[Exception], ...] = (Exception,), handler: Callable[[Exception], Any] | None = None, reraise: bool = False, logger: Logger | None = None) -> Generator[None, None, None]
Context manager to catch and handle exceptions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exceptions
|
tuple[type[Exception], ...]
|
Tuple of exceptions to catch. |
(Exception,)
|
handler
|
Callable[[Exception], Any] | None
|
Optional handler function called with exception. |
None
|
reraise
|
bool
|
If True, reraise exception after handling. |
False
|
logger
|
Logger | None
|
Optional logger to log exceptions. |
None
|
Yields:
| Type | Description |
|---|---|
None
|
None. |
Examples:
errors_format_traceback ¶
Traceback Formatter¶
Format exception tracebacks for better readability.
Examples¶
from rite.diagnostics.errors import errors_format_traceback try: ... 1 / 0 ... except Exception as e: ... print(errors_format_traceback(e))
errors_get_chain ¶
Exception Chain¶
Get exception chain (cause hierarchy).
Examples¶
from rite.diagnostics.errors import errors_get_chain try: ... try: ... 1 / 0 ... except ZeroDivisionError as e: ... raise ValueError("Wrapped") from e ... except ValueError as e: ... chain = errors_get_chain(e)
errors_retry ¶
Retry Decorator¶
Decorator to retry function calls on failure.
Examples¶
from rite.diagnostics.errors import errors_retry @errors_retry(max_attempts=3, delay=1.0) ... def unstable_function(): ... pass
errors_retry(max_attempts: int = 3, delay: float = 1.0, backoff: float = 2.0, exceptions: tuple[type[Exception], ...] = (Exception,)) -> Callable[[Callable[..., T]], Callable[..., T]]
Decorator to retry function on failure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_attempts
|
int
|
Maximum retry attempts. |
3
|
delay
|
float
|
Initial delay between retries (seconds). |
1.0
|
backoff
|
float
|
Multiplier for delay on each retry. |
2.0
|
exceptions
|
tuple[type[Exception], ...]
|
Tuple of exceptions to catch. |
(Exception,)
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., T]], Callable[..., T]]
|
Decorated function with retry logic. |
Examples:
errors_catch ¶
Exception Context Manager¶
Context manager to catch and handle exceptions gracefully.
Examples¶
from rite.diagnostics.errors import errors_catch with errors_catch(): ... risky_operation()
Functions¶
errors_catch ¶
errors_catch(exceptions: tuple[type[Exception], ...] = (Exception,), handler: Callable[[Exception], Any] | None = None, reraise: bool = False, logger: Logger | None = None) -> Generator[None, None, None]
Context manager to catch and handle exceptions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exceptions
|
tuple[type[Exception], ...]
|
Tuple of exceptions to catch. |
(Exception,)
|
handler
|
Callable[[Exception], Any] | None
|
Optional handler function called with exception. |
None
|
reraise
|
bool
|
If True, reraise exception after handling. |
False
|
logger
|
Logger | None
|
Optional logger to log exceptions. |
None
|
Yields:
| Type | Description |
|---|---|
None
|
None. |
Examples:
errors_format_traceback ¶
Traceback Formatter¶
Format exception tracebacks for better readability.
Examples¶
from rite.diagnostics.errors import errors_format_traceback try: ... 1 / 0 ... except Exception as e: ... print(errors_format_traceback(e))
errors_get_chain ¶
Exception Chain¶
Get exception chain (cause hierarchy).
Examples¶
from rite.diagnostics.errors import errors_get_chain try: ... try: ... 1 / 0 ... except ZeroDivisionError as e: ... raise ValueError("Wrapped") from e ... except ValueError as e: ... chain = errors_get_chain(e)
errors_retry ¶
Retry Decorator¶
Decorator to retry function calls on failure.
Examples¶
from rite.diagnostics.errors import errors_retry @errors_retry(max_attempts=3, delay=1.0) ... def unstable_function(): ... pass
Functions¶
errors_retry ¶
errors_retry(max_attempts: int = 3, delay: float = 1.0, backoff: float = 2.0, exceptions: tuple[type[Exception], ...] = (Exception,)) -> Callable[[Callable[..., T]], Callable[..., T]]
Decorator to retry function on failure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_attempts
|
int
|
Maximum retry attempts. |
3
|
delay
|
float
|
Initial delay between retries (seconds). |
1.0
|
backoff
|
float
|
Multiplier for delay on each retry. |
2.0
|
exceptions
|
tuple[type[Exception], ...]
|
Tuple of exceptions to catch. |
(Exception,)
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., T]], Callable[..., T]]
|
Decorated function with retry logic. |
Examples:
logger ¶
Logger Module¶
This module provides the Logger class, which serves as a simple and
configurable logging utility for applications within the Sense ecosystem.
It supports logging to both the console and a file, includes timestamped
messages, and provides different logging levels such as debug, info, warning,
error, and critical.
Classes:¶
- Logger: A configurable logger for managing log messages in applications.
Features:¶
- Log to console and/or file.
- Timestamped messages for traceability.
- Logging levels: debug, info, warning, error, critical.
- Clear log file utility.
Classes¶
Logger ¶
Logger Class¶
A configurable logger that supports logging to both console and file outputs with various log levels. This class wraps Python's built-in logging module, providing an easy interface to integrate logging into applications.
Attributes¶
logger : logging.Logger The underlying logger instance from Python's logging module. log_file : str | None Path to the log file if file logging is enabled.
Initializes a new Logger instance with the specified name and optional log file.
Parameters:¶
name : str The name of the logger, typically the module or application name. log_file : str | None Path to a log file for file logging. If None, logging to file is disabled.
Example:¶
logger = Logger(name="MyApp", log_file="app.log") logger.info("Application started")
logging ¶
Logging Module¶
Logging utilities with file, console, structured, and contextual output.
This submodule provides various logging configurations for different use cases: file logging with rotation, console logging with colors, structured JSON logging, and context-aware logging.
Examples¶
from rite.diagnostics.logging import ( ... logging_to_file, ... logging_to_console, ... logging_structured ... ) file_logger = logging_to_file("app", "app.log") console_logger = logging_to_console("debug", colorize=True) struct_logger = logging_structured("api")
Modules¶
logging_structured ¶
Structured Logger¶
Logger with structured output (JSON, key-value pairs).
Examples¶
from rite.diagnostics.logging import logging_structured logger = logging_structured("app") logger.info("User logged in", user_id=123, ip="192.168.1.1")
logging_structured(name: str, level: int = logging.INFO, json_format: bool = True) -> logging.Logger
Create logger with structured output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logger name. |
required |
level
|
int
|
Logging level (default INFO). |
INFO
|
json_format
|
bool
|
If True, output as JSON; else key=value format. |
True
|
Returns:
| Type | Description |
|---|---|
Logger
|
Configured logger with structured formatter. |
Examples:
logging_to_console ¶
Console Logger¶
Create logger that writes to console/stdout.
Examples¶
from rite.diagnostics.logging import logging_to_console logger = logging_to_console("app") logger.info("Application started")
logging_to_console(name: str, level: int = logging.INFO, format_string: str | None = None, colorize: bool = False) -> logging.Logger
Create logger that writes to console.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logger name. |
required |
level
|
int
|
Logging level (default INFO). |
INFO
|
format_string
|
str | None
|
Custom format string. |
None
|
colorize
|
bool
|
If True, colorize output by level. |
False
|
Returns:
| Type | Description |
|---|---|
Logger
|
Configured console logger. |
Examples:
logging_to_file ¶
File Logger¶
Create logger that writes to a file with rotation support.
Examples¶
from rite.diagnostics.logging import logging_to_file logger = logging_to_file("app", "app.log") logger.info("Application started")
logging_to_file(name: str, filepath: str, level: int = logging.INFO, max_bytes: int = 10485760, backup_count: int = 5, format_string: str | None = None) -> logging.Logger
Create logger that writes to a file with rotation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logger name. |
required |
filepath
|
str
|
Path to log file. |
required |
level
|
int
|
Logging level (default INFO). |
INFO
|
max_bytes
|
int
|
Max file size before rotation (default 10MB). |
10485760
|
backup_count
|
int
|
Number of backup files to keep (default 5). |
5
|
format_string
|
str | None
|
Custom format string. |
None
|
Returns:
| Type | Description |
|---|---|
Logger
|
Configured file logger. |
Examples:
logging_with_context ¶
Context Logger¶
Logger that includes contextual information in all messages.
Examples¶
from rite.diagnostics.logging import logging_with_context logger = logging_with_context("app", request_id="abc123") logger.info("Processing request")
Create logger that includes context in all messages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logger name. |
required |
level
|
int
|
Logging level (default INFO). |
INFO
|
**context
|
Any
|
Context key-value pairs to include. |
{}
|
Returns:
| Type | Description |
|---|---|
LoggerAdapter
|
Logger adapter with context. |
Examples:
logging_structured ¶
Structured Logger¶
Logger with structured output (JSON, key-value pairs).
Examples¶
from rite.diagnostics.logging import logging_structured logger = logging_structured("app") logger.info("User logged in", user_id=123, ip="192.168.1.1")
Functions¶
logging_structured ¶
logging_structured(name: str, level: int = logging.INFO, json_format: bool = True) -> logging.Logger
Create logger with structured output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logger name. |
required |
level
|
int
|
Logging level (default INFO). |
INFO
|
json_format
|
bool
|
If True, output as JSON; else key=value format. |
True
|
Returns:
| Type | Description |
|---|---|
Logger
|
Configured logger with structured formatter. |
Examples:
logging_to_console ¶
Console Logger¶
Create logger that writes to console/stdout.
Examples¶
from rite.diagnostics.logging import logging_to_console logger = logging_to_console("app") logger.info("Application started")
Functions¶
logging_to_console ¶
logging_to_console(name: str, level: int = logging.INFO, format_string: str | None = None, colorize: bool = False) -> logging.Logger
Create logger that writes to console.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logger name. |
required |
level
|
int
|
Logging level (default INFO). |
INFO
|
format_string
|
str | None
|
Custom format string. |
None
|
colorize
|
bool
|
If True, colorize output by level. |
False
|
Returns:
| Type | Description |
|---|---|
Logger
|
Configured console logger. |
Examples:
logging_to_file ¶
File Logger¶
Create logger that writes to a file with rotation support.
Examples¶
from rite.diagnostics.logging import logging_to_file logger = logging_to_file("app", "app.log") logger.info("Application started")
Functions¶
logging_to_file ¶
logging_to_file(name: str, filepath: str, level: int = logging.INFO, max_bytes: int = 10485760, backup_count: int = 5, format_string: str | None = None) -> logging.Logger
Create logger that writes to a file with rotation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logger name. |
required |
filepath
|
str
|
Path to log file. |
required |
level
|
int
|
Logging level (default INFO). |
INFO
|
max_bytes
|
int
|
Max file size before rotation (default 10MB). |
10485760
|
backup_count
|
int
|
Number of backup files to keep (default 5). |
5
|
format_string
|
str | None
|
Custom format string. |
None
|
Returns:
| Type | Description |
|---|---|
Logger
|
Configured file logger. |
Examples:
logging_with_context ¶
Context Logger¶
Logger that includes contextual information in all messages.
Examples¶
from rite.diagnostics.logging import logging_with_context logger = logging_with_context("app", request_id="abc123") logger.info("Processing request")
Functions¶
logging_with_context ¶
Create logger that includes context in all messages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logger name. |
required |
level
|
int
|
Logging level (default INFO). |
INFO
|
**context
|
Any
|
Context key-value pairs to include. |
{}
|
Returns:
| Type | Description |
|---|---|
LoggerAdapter
|
Logger adapter with context. |
Examples:
metrics ¶
Metrics Module¶
Performance and monitoring metrics.
This submodule provides metric classes for counters, gauges, histograms, and timers.
Examples¶
from rite.diagnostics.metrics import ( ... metrics_counter, ... metrics_gauge, ... metrics_histogram, ... metrics_timer ... ) counter = metrics_counter("requests") counter.increment()
Modules¶
metrics_counter ¶
Counter Metric¶
Counter that can only increase.
Examples¶
from rite.diagnostics.metrics import metrics_counter counter = metrics_counter("requests") counter.increment() counter.value 1
Counter metric that only increases.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Metric name. |
|
value |
float
|
Current counter value. |
Examples:
>>> counter = metrics_counter("api_calls")
>>> counter.increment()
>>> counter.increment(5)
>>> counter.value
6
Initialize counter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Metric name. |
required |
metrics_gauge ¶
Gauge Metric¶
Gauge that can increase or decrease.
Examples¶
from rite.diagnostics.metrics import metrics_gauge gauge = metrics_gauge("temperature") gauge.set(25.0) gauge.value 25.0
Gauge metric that can go up or down.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Metric name. |
|
value |
float
|
Current gauge value. |
Examples:
>>> gauge = metrics_gauge("memory_usage")
>>> gauge.set(100)
>>> gauge.increment(50)
>>> gauge.decrement(25)
>>> gauge.value
125.0
Initialize gauge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Metric name. |
required |
initial_value
|
float
|
Starting value. |
0.0
|
metrics_histogram ¶
Histogram Metric¶
Histogram to track distribution of values.
Examples¶
from rite.diagnostics.metrics import metrics_histogram hist = metrics_histogram("response_time") hist.observe(0.5) hist.count 1
Histogram metric for value distributions.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Metric name. |
|
count |
int
|
Number of observations. |
sum |
float
|
Sum of all values. |
Examples:
>>> hist = metrics_histogram("latency")
>>> hist.observe(1.0)
>>> hist.observe(2.0)
>>> hist.observe(3.0)
>>> hist.mean
2.0
Initialize histogram.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Metric name. |
required |
metrics_timer ¶
Timer Metric¶
Timer to measure durations as context manager.
Examples¶
from rite.diagnostics.metrics import metrics_timer timer = metrics_timer("operation") with timer: ... pass timer.count 1
Timer metric using context manager.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Metric name. |
|
count |
int
|
Number of timing measurements. |
total |
float
|
Total time measured. |
Examples:
>>> timer = metrics_timer("request")
>>> with timer:
... time.sleep(0.01)
>>> timer.count
1
>>> timer.total > 0
True
Initialize timer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Metric name. |
required |
metrics_counter ¶
Counter Metric¶
Counter that can only increase.
Examples¶
from rite.diagnostics.metrics import metrics_counter counter = metrics_counter("requests") counter.increment() counter.value 1
Classes¶
metrics_counter ¶
Counter metric that only increases.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Metric name. |
|
value |
float
|
Current counter value. |
Examples:
>>> counter = metrics_counter("api_calls")
>>> counter.increment()
>>> counter.increment(5)
>>> counter.value
6
Initialize counter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Metric name. |
required |
metrics_gauge ¶
Gauge Metric¶
Gauge that can increase or decrease.
Examples¶
from rite.diagnostics.metrics import metrics_gauge gauge = metrics_gauge("temperature") gauge.set(25.0) gauge.value 25.0
Classes¶
metrics_gauge ¶
Gauge metric that can go up or down.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Metric name. |
|
value |
float
|
Current gauge value. |
Examples:
>>> gauge = metrics_gauge("memory_usage")
>>> gauge.set(100)
>>> gauge.increment(50)
>>> gauge.decrement(25)
>>> gauge.value
125.0
Initialize gauge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Metric name. |
required |
initial_value
|
float
|
Starting value. |
0.0
|
metrics_histogram ¶
Histogram Metric¶
Histogram to track distribution of values.
Examples¶
from rite.diagnostics.metrics import metrics_histogram hist = metrics_histogram("response_time") hist.observe(0.5) hist.count 1
Classes¶
metrics_histogram ¶
Histogram metric for value distributions.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Metric name. |
|
count |
int
|
Number of observations. |
sum |
float
|
Sum of all values. |
Examples:
>>> hist = metrics_histogram("latency")
>>> hist.observe(1.0)
>>> hist.observe(2.0)
>>> hist.observe(3.0)
>>> hist.mean
2.0
Initialize histogram.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Metric name. |
required |
metrics_timer ¶
Timer Metric¶
Timer to measure durations as context manager.
Examples¶
from rite.diagnostics.metrics import metrics_timer timer = metrics_timer("operation") with timer: ... pass timer.count 1
Classes¶
metrics_timer ¶
Timer metric using context manager.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Metric name. |
|
count |
int
|
Number of timing measurements. |
total |
float
|
Total time measured. |
Examples:
>>> timer = metrics_timer("request")
>>> with timer:
... time.sleep(0.01)
>>> timer.count
1
>>> timer.total > 0
True
Initialize timer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Metric name. |
required |
profiling ¶
Profiling Module¶
Performance profiling utilities.
This submodule provides utilities for measuring execution time, memory usage, and function call counts.
Examples¶
from rite.diagnostics.profiling import ( ... profiling_timer, ... profiling_stopwatch, ... profiling_memory ... ) @profiling_timer() ... def slow_function(): ... pass with profiling_stopwatch("task") as sw: ... pass
Modules¶
profiling_count_calls ¶
Function Call Counter¶
Count how many times a function is called.
Examples¶
from rite.diagnostics.profiling import profiling_count_calls @profiling_count_calls() ... def api_call(): ... pass
profiling_count_calls(print_every: int | None = None) -> Callable[[Callable[..., T]], Callable[..., T]]
Decorator to count function calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
print_every
|
int | None
|
Print count every N calls (None = don't print). |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., T]], Callable[..., T]]
|
Decorated function with call counter. |
Examples:
profiling_memory ¶
Memory Profiler¶
Measure memory usage of function.
Examples¶
from rite.diagnostics.profiling import profiling_memory @profiling_memory() ... def memory_intensive(): ... data = [0] * 1000000
Decorator to measure memory usage of function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
print_result
|
bool
|
If True, print memory usage. |
True
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., T]], Callable[..., T]]
|
Decorated function that measures memory. |
Examples:
>>> @profiling_memory()
... def create_large_list():
... return [0] * 1000000
>>> @profiling_memory(print_result=False)
... def process_data():
... pass
Notes
Uses sys.getsizeof for basic measurement. For detailed profiling, use memory_profiler package.
profiling_stopwatch ¶
Timer Context Manager¶
Context manager to measure elapsed time.
Examples¶
from rite.diagnostics.profiling import profiling_stopwatch with profiling_stopwatch("operation") as sw: ... time.sleep(0.1) print(sw.elapsed)
Context manager to measure elapsed time.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Operation name. |
|
elapsed |
float
|
Elapsed time in seconds. |
start_time |
float
|
Start timestamp. |
end_time |
float
|
End timestamp. |
Examples:
Initialize stopwatch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Operation name for display. |
'operation'
|
profiling_timer ¶
Timer Decorator¶
Decorator to measure function execution time.
Examples¶
from rite.diagnostics.profiling import profiling_timer @profiling_timer() ... def slow_function(): ... time.sleep(1)
profiling_timer(name: str | None = None, print_result: bool = True) -> Callable[[Callable[..., T]], Callable[..., T]]
Decorator to measure function execution time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
Optional name for the operation being timed. |
None
|
print_result
|
bool
|
If True, print timing result. |
True
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., T]], Callable[..., T]]
|
Decorated function that measures execution time. |
Examples:
profiling_count_calls ¶
Function Call Counter¶
Count how many times a function is called.
Examples¶
from rite.diagnostics.profiling import profiling_count_calls @profiling_count_calls() ... def api_call(): ... pass
Functions¶
profiling_count_calls ¶
profiling_count_calls(print_every: int | None = None) -> Callable[[Callable[..., T]], Callable[..., T]]
Decorator to count function calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
print_every
|
int | None
|
Print count every N calls (None = don't print). |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., T]], Callable[..., T]]
|
Decorated function with call counter. |
Examples:
profiling_memory ¶
Memory Profiler¶
Measure memory usage of function.
Examples¶
from rite.diagnostics.profiling import profiling_memory @profiling_memory() ... def memory_intensive(): ... data = [0] * 1000000
Functions¶
profiling_memory ¶
Decorator to measure memory usage of function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
print_result
|
bool
|
If True, print memory usage. |
True
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., T]], Callable[..., T]]
|
Decorated function that measures memory. |
Examples:
>>> @profiling_memory()
... def create_large_list():
... return [0] * 1000000
>>> @profiling_memory(print_result=False)
... def process_data():
... pass
Notes
Uses sys.getsizeof for basic measurement. For detailed profiling, use memory_profiler package.
profiling_stopwatch ¶
Timer Context Manager¶
Context manager to measure elapsed time.
Examples¶
from rite.diagnostics.profiling import profiling_stopwatch with profiling_stopwatch("operation") as sw: ... time.sleep(0.1) print(sw.elapsed)
Classes¶
profiling_stopwatch ¶
Context manager to measure elapsed time.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Operation name. |
|
elapsed |
float
|
Elapsed time in seconds. |
start_time |
float
|
Start timestamp. |
end_time |
float
|
End timestamp. |
Examples:
Initialize stopwatch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Operation name for display. |
'operation'
|
profiling_timer ¶
Timer Decorator¶
Decorator to measure function execution time.
Examples¶
from rite.diagnostics.profiling import profiling_timer @profiling_timer() ... def slow_function(): ... time.sleep(1)
Functions¶
profiling_timer ¶
profiling_timer(name: str | None = None, print_result: bool = True) -> Callable[[Callable[..., T]], Callable[..., T]]
Decorator to measure function execution time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
Optional name for the operation being timed. |
None
|
print_result
|
bool
|
If True, print timing result. |
True
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., T]], Callable[..., T]]
|
Decorated function that measures execution time. |
Examples:
Submodules¶
Logging¶
Structured logging utilities.
Logging Module¶
Logging utilities with file, console, structured, and contextual output.
This submodule provides various logging configurations for different use cases: file logging with rotation, console logging with colors, structured JSON logging, and context-aware logging.
Examples¶
from rite.diagnostics.logging import ( ... logging_to_file, ... logging_to_console, ... logging_structured ... ) file_logger = logging_to_file("app", "app.log") console_logger = logging_to_console("debug", colorize=True) struct_logger = logging_structured("api")
Modules¶
logging_to_console ¶
Console Logger¶
Create logger that writes to console/stdout.
Examples¶
from rite.diagnostics.logging import logging_to_console logger = logging_to_console("app") logger.info("Application started")
Functions¶
logging_to_console ¶
logging_to_console(name: str, level: int = logging.INFO, format_string: str | None = None, colorize: bool = False) -> logging.Logger
Create logger that writes to console.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logger name. |
required |
level
|
int
|
Logging level (default INFO). |
INFO
|
format_string
|
str | None
|
Custom format string. |
None
|
colorize
|
bool
|
If True, colorize output by level. |
False
|
Returns:
| Type | Description |
|---|---|
Logger
|
Configured console logger. |
Examples:
logging_to_file ¶
File Logger¶
Create logger that writes to a file with rotation support.
Examples¶
from rite.diagnostics.logging import logging_to_file logger = logging_to_file("app", "app.log") logger.info("Application started")
Functions¶
logging_to_file ¶
logging_to_file(name: str, filepath: str, level: int = logging.INFO, max_bytes: int = 10485760, backup_count: int = 5, format_string: str | None = None) -> logging.Logger
Create logger that writes to a file with rotation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logger name. |
required |
filepath
|
str
|
Path to log file. |
required |
level
|
int
|
Logging level (default INFO). |
INFO
|
max_bytes
|
int
|
Max file size before rotation (default 10MB). |
10485760
|
backup_count
|
int
|
Number of backup files to keep (default 5). |
5
|
format_string
|
str | None
|
Custom format string. |
None
|
Returns:
| Type | Description |
|---|---|
Logger
|
Configured file logger. |
Examples:
logging_structured ¶
Structured Logger¶
Logger with structured output (JSON, key-value pairs).
Examples¶
from rite.diagnostics.logging import logging_structured logger = logging_structured("app") logger.info("User logged in", user_id=123, ip="192.168.1.1")
Functions¶
logging_structured ¶
logging_structured(name: str, level: int = logging.INFO, json_format: bool = True) -> logging.Logger
Create logger with structured output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logger name. |
required |
level
|
int
|
Logging level (default INFO). |
INFO
|
json_format
|
bool
|
If True, output as JSON; else key=value format. |
True
|
Returns:
| Type | Description |
|---|---|
Logger
|
Configured logger with structured formatter. |
Examples:
logging_with_context ¶
Context Logger¶
Logger that includes contextual information in all messages.
Examples¶
from rite.diagnostics.logging import logging_with_context logger = logging_with_context("app", request_id="abc123") logger.info("Processing request")
Functions¶
logging_with_context ¶
Create logger that includes context in all messages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logger name. |
required |
level
|
int
|
Logging level (default INFO). |
INFO
|
**context
|
Any
|
Context key-value pairs to include. |
{}
|
Returns:
| Type | Description |
|---|---|
LoggerAdapter
|
Logger adapter with context. |
Examples:
Profiling¶
Performance profiling tools.
Profiling Module¶
Performance profiling utilities.
This submodule provides utilities for measuring execution time, memory usage, and function call counts.
Examples¶
from rite.diagnostics.profiling import ( ... profiling_timer, ... profiling_stopwatch, ... profiling_memory ... ) @profiling_timer() ... def slow_function(): ... pass with profiling_stopwatch("task") as sw: ... pass
Modules¶
profiling_timer ¶
Timer Decorator¶
Decorator to measure function execution time.
Examples¶
from rite.diagnostics.profiling import profiling_timer @profiling_timer() ... def slow_function(): ... time.sleep(1)
Functions¶
profiling_timer ¶
profiling_timer(name: str | None = None, print_result: bool = True) -> Callable[[Callable[..., T]], Callable[..., T]]
Decorator to measure function execution time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
Optional name for the operation being timed. |
None
|
print_result
|
bool
|
If True, print timing result. |
True
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., T]], Callable[..., T]]
|
Decorated function that measures execution time. |
Examples:
profiling_stopwatch ¶
Timer Context Manager¶
Context manager to measure elapsed time.
Examples¶
from rite.diagnostics.profiling import profiling_stopwatch with profiling_stopwatch("operation") as sw: ... time.sleep(0.1) print(sw.elapsed)
Classes¶
profiling_stopwatch ¶
Context manager to measure elapsed time.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Operation name. |
|
elapsed |
float
|
Elapsed time in seconds. |
start_time |
float
|
Start timestamp. |
end_time |
float
|
End timestamp. |
Examples:
Initialize stopwatch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Operation name for display. |
'operation'
|
profiling_memory ¶
Memory Profiler¶
Measure memory usage of function.
Examples¶
from rite.diagnostics.profiling import profiling_memory @profiling_memory() ... def memory_intensive(): ... data = [0] * 1000000
Functions¶
profiling_memory ¶
Decorator to measure memory usage of function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
print_result
|
bool
|
If True, print memory usage. |
True
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., T]], Callable[..., T]]
|
Decorated function that measures memory. |
Examples:
>>> @profiling_memory()
... def create_large_list():
... return [0] * 1000000
>>> @profiling_memory(print_result=False)
... def process_data():
... pass
Notes
Uses sys.getsizeof for basic measurement. For detailed profiling, use memory_profiler package.
profiling_count_calls ¶
Function Call Counter¶
Count how many times a function is called.
Examples¶
from rite.diagnostics.profiling import profiling_count_calls @profiling_count_calls() ... def api_call(): ... pass
Functions¶
profiling_count_calls ¶
profiling_count_calls(print_every: int | None = None) -> Callable[[Callable[..., T]], Callable[..., T]]
Decorator to count function calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
print_every
|
int | None
|
Print count every N calls (None = don't print). |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., T]], Callable[..., T]]
|
Decorated function with call counter. |
Examples:
Error Handling¶
Error management utilities.
Error Handling Module¶
Error handling utilities with retry, catching, and formatting.
This submodule provides utilities for handling errors gracefully: retry decorators, exception context managers, traceback formatting, and exception chain analysis.
Examples¶
from rite.diagnostics.errors import errors_retry, errors_catch @errors_retry(max_attempts=3) ... def flaky_function(): ... pass with errors_catch(): ... risky_operation()
Modules¶
errors_catch ¶
Exception Context Manager¶
Context manager to catch and handle exceptions gracefully.
Examples¶
from rite.diagnostics.errors import errors_catch with errors_catch(): ... risky_operation()
Functions¶
errors_catch ¶
errors_catch(exceptions: tuple[type[Exception], ...] = (Exception,), handler: Callable[[Exception], Any] | None = None, reraise: bool = False, logger: Logger | None = None) -> Generator[None, None, None]
Context manager to catch and handle exceptions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exceptions
|
tuple[type[Exception], ...]
|
Tuple of exceptions to catch. |
(Exception,)
|
handler
|
Callable[[Exception], Any] | None
|
Optional handler function called with exception. |
None
|
reraise
|
bool
|
If True, reraise exception after handling. |
False
|
logger
|
Logger | None
|
Optional logger to log exceptions. |
None
|
Yields:
| Type | Description |
|---|---|
None
|
None. |
Examples:
errors_retry ¶
Retry Decorator¶
Decorator to retry function calls on failure.
Examples¶
from rite.diagnostics.errors import errors_retry @errors_retry(max_attempts=3, delay=1.0) ... def unstable_function(): ... pass
Functions¶
errors_retry ¶
errors_retry(max_attempts: int = 3, delay: float = 1.0, backoff: float = 2.0, exceptions: tuple[type[Exception], ...] = (Exception,)) -> Callable[[Callable[..., T]], Callable[..., T]]
Decorator to retry function on failure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_attempts
|
int
|
Maximum retry attempts. |
3
|
delay
|
float
|
Initial delay between retries (seconds). |
1.0
|
backoff
|
float
|
Multiplier for delay on each retry. |
2.0
|
exceptions
|
tuple[type[Exception], ...]
|
Tuple of exceptions to catch. |
(Exception,)
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., T]], Callable[..., T]]
|
Decorated function with retry logic. |
Examples:
errors_get_chain ¶
Exception Chain¶
Get exception chain (cause hierarchy).
Examples¶
from rite.diagnostics.errors import errors_get_chain try: ... try: ... 1 / 0 ... except ZeroDivisionError as e: ... raise ValueError("Wrapped") from e ... except ValueError as e: ... chain = errors_get_chain(e)
errors_format_traceback ¶
Traceback Formatter¶
Format exception tracebacks for better readability.
Examples¶
from rite.diagnostics.errors import errors_format_traceback try: ... 1 / 0 ... except Exception as e: ... print(errors_format_traceback(e))
Metrics¶
Application metrics collection.
Metrics Module¶
Performance and monitoring metrics.
This submodule provides metric classes for counters, gauges, histograms, and timers.
Examples¶
from rite.diagnostics.metrics import ( ... metrics_counter, ... metrics_gauge, ... metrics_histogram, ... metrics_timer ... ) counter = metrics_counter("requests") counter.increment()
Modules¶
metrics_counter ¶
Counter Metric¶
Counter that can only increase.
Examples¶
from rite.diagnostics.metrics import metrics_counter counter = metrics_counter("requests") counter.increment() counter.value 1
Classes¶
metrics_counter ¶
Counter metric that only increases.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Metric name. |
|
value |
float
|
Current counter value. |
Examples:
>>> counter = metrics_counter("api_calls")
>>> counter.increment()
>>> counter.increment(5)
>>> counter.value
6
Initialize counter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Metric name. |
required |
metrics_gauge ¶
Gauge Metric¶
Gauge that can increase or decrease.
Examples¶
from rite.diagnostics.metrics import metrics_gauge gauge = metrics_gauge("temperature") gauge.set(25.0) gauge.value 25.0
Classes¶
metrics_gauge ¶
Gauge metric that can go up or down.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Metric name. |
|
value |
float
|
Current gauge value. |
Examples:
>>> gauge = metrics_gauge("memory_usage")
>>> gauge.set(100)
>>> gauge.increment(50)
>>> gauge.decrement(25)
>>> gauge.value
125.0
Initialize gauge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Metric name. |
required |
initial_value
|
float
|
Starting value. |
0.0
|
metrics_timer ¶
Timer Metric¶
Timer to measure durations as context manager.
Examples¶
from rite.diagnostics.metrics import metrics_timer timer = metrics_timer("operation") with timer: ... pass timer.count 1
Classes¶
metrics_timer ¶
Timer metric using context manager.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Metric name. |
|
count |
int
|
Number of timing measurements. |
total |
float
|
Total time measured. |
Examples:
>>> timer = metrics_timer("request")
>>> with timer:
... time.sleep(0.01)
>>> timer.count
1
>>> timer.total > 0
True
Initialize timer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Metric name. |
required |
metrics_histogram ¶
Histogram Metric¶
Histogram to track distribution of values.
Examples¶
from rite.diagnostics.metrics import metrics_histogram hist = metrics_histogram("response_time") hist.observe(0.5) hist.count 1
Classes¶
metrics_histogram ¶
Histogram metric for value distributions.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Metric name. |
|
count |
int
|
Number of observations. |
sum |
float
|
Sum of all values. |
Examples:
>>> hist = metrics_histogram("latency")
>>> hist.observe(1.0)
>>> hist.observe(2.0)
>>> hist.observe(3.0)
>>> hist.mean
2.0
Initialize histogram.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Metric name. |
required |
Examples¶
from rite.diagnostics import (
profiling_timer,
errors_retry,
metrics_counter
)
# Time function execution
@profiling_timer
def slow_function():
# ... code ...
pass
# Retry on failure
@errors_retry(max_attempts=3)
def unstable_operation():
# ... code ...
pass
# Count metrics
counter = metrics_counter("requests")
counter.increment()