Utilities for logging, assertions and custom exceptions
Project description
Logguard
Logguard is a lightweight logging and assertion library designed to make it easy to capture rich context and structured logs in Python applications. It provides a simple API for logging with automatic source capture, flexible configuration, and a semantic exception hierarchy.
It is built on top of the logging and rich libraries for enhanced logging capabilities.
⭐ Features
- Easy Configuration: Set up logging in one line with
AppLogger - File Rotation: Automatic log rotation with configurable size and backup count
- Rich Console Output: Beautiful console logs with Rich support
- JSON Logging: Optional structured JSON output for log aggregation systems
- Smart Assertions:
ASSERTandenforcewith automatic source capture and logging - Semantic Exceptions: Clear exception hierarchy (
ValidationError,ConfigurationError, etc.) - Fast Startup: Lazy imports for minimal performance impact
- Library Silencing: Automatically suppresses noisy third-party library logs
Installation
Install with pip or your favorite PyPI package manager.
python -m pip install py-logguard
For development with optional dependencies:
python -m pip install py-logguard[dev]
For JSON logging support:
python -m pip install py-logguard[json]
🚩 Quick Start
Logging
Logguard provides a simple way to configure logging with sensible defaults. Just call setup() once and you're ready to go.
from logguard import AppLogger
AppLogger.setup(log_file="logs/app.log", console_level="INFO")
logger = AppLogger.get_logger(__name__)
logger.info("Application started")
logger.debug("Debug info")
logger.warning("Warning")
logger.error("Error occurred")
Logging will output to both console and file, with automatic rotation when files get too large.
Assertions
Use ASSERT to validate conditions while automatically capturing context like file, line, function, and the expression itself.
from logguard import ASSERT
from logguard.exceptions import ValidationError
def validate_user(name: str, age: int):
ASSERT(bool(name), "Name cannot be empty")
ASSERT(len(name) >= 2, "Name must have at least 2 characters")
ASSERT(age >= 0, "Age must be positive")
ASSERT(age <= 150, "Age seems unrealistic")
try:
validate_user("", 25)
except ValidationError as e:
logger.error(f"Validation failed: {e}")
When an assertion fails, logguard logs the full context and raises a ValidationError with rich details for debugging.
Specialized Assertions
Logguard includes helpers for common validation patterns:
from logguard import (
ASSERT_TYPE, ASSERT_NOT_NONE, ASSERT_NOT_EMPTY,
ASSERT_IN, ASSERT_RANGE, ASSERT_EQUALS
)
ASSERT_TYPE(user, dict, "Expected a dictionary")
ASSERT_NOT_NONE(email, "Email is required")
ASSERT_NOT_EMPTY(name, "Name cannot be empty")
ASSERT_IN(status, ["active", "inactive"], "Invalid status")
ASSERT_RANGE(age, 0, 150, "Age out of range")
ASSERT_EQUALS(total, 100, "Total must be 100")
These functions provide cleaner, more readable assertions for specific use cases.
Custom Exceptions
Logguard provides a semantic exception hierarchy for clearer error handling:
from logguard.exceptions import (
ValidationError, ConfigurationError, ResourceNotFoundError
)
# Validation errors (from ASSERT failures)
raise ValidationError("Invalid input", field="email")
# Configuration errors
raise ConfigurationError("Invalid config", file_path="config.json")
# Resource errors
raise ResourceNotFoundError("User", identifier=123)
All exceptions include rich context information accessible via .to_dict() for logging.
JSON Logging
For production environments, enable JSON logs for structured log aggregation:
from logguard import AppLogger
AppLogger.setup(json_logs=True)
logger = AppLogger.get_logger(__name__)
logger.info("User logged in", extra={"user_id": 123})
logger.error("Database error", extra={"error_code": "DB_001"})
Enable via environment variable: export JSON_LOGS=true
Requires: pip install py-logguard[json]
See the
examples/folder for more complete demonstrations.
📚 API Reference
AppLogger - Logging Configuration & Management
AppLogger is the main interface for logging. Configure it once and get loggers throughout your application.
Setup:
AppLogger.setup(
log_file="logs/app.log", # Path to log file
console_level="INFO", # Console output level
file_level="DEBUG", # File output level
json_logs=False, # Enable JSON formatting
max_bytes=5_000_000, # Max file size before rotation (bytes)
backup_count=3, # Number of rotated backups to keep
force=False # 'True' will override existing handlers
)
Methods:
get_logger(name: str | None = None)- Get or create a logger instanceset_level(level: str, handler_type: str = "all")- Dynamically change log level ("console", "file", or "all")reset()- Reset configuration (useful for testing)
Example:
AppLogger.setup(log_file="logs/app.log")
logger = AppLogger.get_logger(__name__)
logger.info("Starting application")
AppLogger.set_level("DEBUG") # Change all handlers to DEBUG
Assertions - Validation with Auto-Context
Assertions validate conditions and automatically capture context (file, line, function, expression) for debugging.
Basic:
ASSERT(condition, message="")- Validate condition, auto-captures source contextenforce(condition, message, expression, filename, line, function, extra=None)- Manual assertion with explicit context
Specialized:
ASSERT_TYPE(value, dict, "Expected dictionary") # Type checking
ASSERT_NOT_NONE(email, "Email required") # Non-None check
ASSERT_NOT_EMPTY(name, "Name cannot be empty") # Non-empty check
ASSERT_IN(status, ["active", "inactive"], "Invalid") # Membership check
ASSERT_RANGE(age, 18, 65, "Age out of range") # Range check
ASSERT_EQUALS(count, 5, "Expected 5 items") # Equality check
Configuration:
from logguard import set_failure_handler
def custom_handler(message, expression, filename, line, function, extra):
# Handle assertion failure your way
print(f"Failed: {expression} at {filename}:{line}")
set_failure_handler(custom_handler)
On Failure:
- Logs the assertion details with context
- Raises
ValidationErrorwith full debugging information
Exceptions - Semantic Error Hierarchy
All exceptions inherit from AppBaseError and include rich context information.
Properties:
message- Error descriptioncontext- Additional context data (dict).to_dict()- Serialize to dictionary for logging
Hierarchy:
AppBaseError
├── ConfigurationError
│ └── MissingConfigError
├── ValidationError (raised by ASSERT)
└── ResourceError
├── ResourceNotFoundError
└── ForbiddenError
Usage Examples:
from logguard.exceptions import (
ValidationError,
ConfigurationError,
ResourceNotFoundError,
)
# Configuration errors
raise ConfigurationError("Invalid config", file_path="config.json")
raise MissingConfigError("DATABASE_URL", source=".env")
# Validation errors
raise ValidationError("Invalid email", field="email", value="invalid")
# Resource errors
raise ResourceNotFoundError("User", identifier=123)
raise ForbiddenError("Access denied for user", user_id=456)
# Serialize for logging
try:
raise ValidationError("Invalid input", field="username")
except ValidationError as e:
logger.exception(f"Error details: {e.to_dict()}")
🤝 Contributing
Contributions, issues and feature requests are welcome.
Feel free to check the issues page.
📜 License
Happy coding! ❤️
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file py_logguard-0.2.0.tar.gz.
File metadata
- Download URL: py_logguard-0.2.0.tar.gz
- Upload date:
- Size: 32.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f50eb1db7721d7dbeea5bdeae107850415e8bc92bdaf7bdadbf97a0ec6065ed9
|
|
| MD5 |
faecd5d084e627c5e158809c7ee42385
|
|
| BLAKE2b-256 |
2b48291a4175efe372b33b02fe140e601105de1d41661706d9f44b4588bd6d8c
|
File details
Details for the file py_logguard-0.2.0-py3-none-any.whl.
File metadata
- Download URL: py_logguard-0.2.0-py3-none-any.whl
- Upload date:
- Size: 17.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2113ce4a28b1c5f26a618d04c110ae460f2b4eb5c71565d189293b04123386fd
|
|
| MD5 |
6de47609e8c72587ae3372c4bbaa622e
|
|
| BLAKE2b-256 |
cb0bc510a48aa8c7e41b83c83ef4ff3a047facfbd1552318911b8e2592fc440a
|