A simple Python logging utility for colorful terminal output
Project description
๐ญ Log Candy
Log Candy is a delightful and powerful Python logging utility that transforms your debugging experience with colorful, well-formatted terminal output. Whether you're debugging complex data structures, monitoring application flow, or building interactive tools, Log Candy makes your logs both beautiful and informative.
โจ Features
- ๐ 5 Color-Coded Log Levels: Each log type has its distinct color for instant visual recognition
- ๐ฏ Universal Object Support: Log strings, numbers, lists, dictionaries, custom objects - anything!
- ๐๏ธ Smart Log Level Filtering: Show only the logs you need with configurable minimum levels
- ๐จ Flexible Formatting Options: Choose between compact and indented formatting for complex objects
- ๐ Progress Bar Integration: Built-in support for tqdm-style progress indicators
- ๏ฟฝ Interactive Debugging: Special input functions for interactive debugging sessions
- ๐ Multiline Support: Automatically handles and properly indents multiline messages
- ๐ Zero Configuration: Works out of the box - just import and start logging
- โก High Performance: Minimal overhead with intelligent formatting thresholds
๐ Quick Start
Installation
Install Log Candy via pip:
pip install log-candy
Basic Usage
from log_candy import log_debug, log_info, log_result, log_warning, log_error
# Simple string logging
log_debug("๐ง Debugging application startup")
log_info("๐ Processing user data")
log_result("โ
Operation completed successfully")
log_warning("โ ๏ธ Low disk space detected")
log_error("โ Failed to connect to database")
Try a Quick Test
Create your own quick test to see Log Candy in action:
from log_candy import *
# Test different object types
log_info("Hello, Log Candy! ๐ญ")
log_debug({"user": "Alice", "score": 95, "active": True})
log_result([1, 2, 3, "success", {"nested": "data"}])
# Control what you see
set_log_level('INFO') # Hide debug messages
log_debug("This won't show")
log_info("This will show!")
๐ Comprehensive Usage Guide
Log Levels & Colors
Log Candy provides 5 distinct log levels, each with its own color and purpose:
| Level | Color | Function | Use Case |
|---|---|---|---|
| ๐ฃ DEBUG | Purple | log_debug() |
Development debugging, detailed tracing |
| ๐ต INFO | Blue | log_info() |
General information, application flow |
| ๐ข RESULT | Green | log_result() |
Important outcomes, successful operations |
| ๐ก WARNING | Yellow | log_warning() |
Potential issues, non-critical problems |
| ๐ด ERROR | Red | log_error() |
Critical errors, failures requiring attention |
from log_candy import *
# All log levels in action
log_debug("๐ Inspecting variable state before processing")
log_info("๐ Starting data analysis pipeline")
log_result("๐ฏ Analysis complete: 1,234 records processed")
log_warning("โ ๏ธ Memory usage is high (85%)")
log_error("๐ฅ Database connection failed after 3 retries")
Object Type Support
Log Candy intelligently handles any Python object type:
# Primitive types
log_info("Simple string message")
log_debug(42) # Numbers
log_result(3.14159) # Floats
log_warning(True) # Booleans
log_info(None) # None values
# Collections (auto-formatted as JSON)
log_info([1, 2, 3, "test", True]) # Lists
log_debug({"name": "Alice", "age": 30, "active": True}) # Dictionaries
log_result((10.5, 20.3, "coordinates")) # Tuples
log_warning({1, 2, 3, 4, 5}) # Sets
# Complex nested structures
user_profile = {
"id": 12345,
"personal": {
"name": "Alice Johnson",
"email": "alice@example.com",
"preferences": {
"theme": "dark",
"notifications": True,
"language": "en"
}
},
"activity": {
"last_login": "2025-08-09T10:30:00Z",
"sessions": [
{"date": "2025-08-09", "duration": 45},
{"date": "2025-08-08", "duration": 32}
]
}
}
log_debug(user_profile) # Beautifully formatted JSON
# Custom objects
class Product:
def __init__(self, name, price, in_stock=True):
self.name = name
self.price = price
self.in_stock = in_stock
def __str__(self):
return f"Product(name='{self.name}', price=${self.price}, in_stock={self.in_stock})"
product = Product("MacBook Pro", 2399.99, True)
log_info(product) # Uses the __str__ method
# Even works with multiline content
multiline_data = """Configuration loaded:
- Database: PostgreSQL
- Cache: Redis
- Queue: RabbitMQ
- Environment: Production"""
log_result(multiline_data) # Properly indented output
Smart Log Level Control
Control which messages are displayed by setting a minimum log level. This is perfect for different environments (development vs production):
from log_candy import set_log_level, get_log_level, LOG_LEVELS
# Show all messages (default)
set_log_level('DEBUG')
log_debug("๐ง Detailed debugging info") # โ
Visible
log_info("๐ General information") # โ
Visible
log_warning("โ ๏ธ Something to watch") # โ
Visible
# Production mode - show only important messages
set_log_level('WARNING')
log_debug("๐ง Debug details") # โ Hidden
log_info("๐ Process started") # โ Hidden
log_warning("โ ๏ธ High memory usage") # โ
Visible
log_error("๐ฅ Critical failure") # โ
Visible
# Check current setting
current_level = get_log_level()
log_info(f"Current log level: {current_level}")
# Available levels (in priority order):
print("๐ Available log levels:", LOG_LEVELS)
# Output: {'DEBUG': 10, 'INFO': 20, 'RESULT': 25, 'WARNING': 30, 'ERROR': 40}
Advanced Formatting Control
Control how complex objects are formatted for optimal readability:
from log_candy import set_compact_formatting, get_formatting_settings
# Example complex object
server_config = {
"database": {
"hosts": ["db1.example.com", "db2.example.com"],
"credentials": {"user": "app_user", "password": "***"},
"pool_size": 20
},
"cache": {"redis_url": "redis://cache.example.com:6379", "ttl": 3600},
"monitoring": {"enabled": True, "endpoints": ["/health", "/metrics"]}
}
# Compact formatting (default) - single line
set_compact_formatting(enabled=True)
log_debug(server_config)
# Output: {"database":{"hosts":["db1.example.com","db2.example.com"]...}
# Indented formatting for readability
set_compact_formatting(enabled=False, threshold=100)
log_debug(server_config)
# Output:
# {
# "database": {
# "hosts": [
# "db1.example.com",
# "db2.example.com"
# ],
# ...
# }
# }
# Hybrid approach - compact for small objects, indented for large ones
set_compact_formatting(enabled=False, threshold=50)
small_obj = {"status": "ok", "count": 5}
log_info(small_obj) # Compact format (under threshold)
log_info(server_config) # Indented format (over threshold)
# Check current settings
settings = get_formatting_settings()
log_debug(f"๐ Current formatting: {settings}")
Special Functions for Advanced Use Cases
Progress Bar Integration
Perfect for monitoring long-running operations:
from log_candy import tqdm_info
import time
# Simulate a progress bar
total_items = 100
for i in range(total_items):
# Your processing logic here
time.sleep(0.01)
# Update progress with colored message
progress_msg = tqdm_info(f"Processing item {i+1}/{total_items} ({((i+1)/total_items)*100:.1f}%)")
print(f"\r{progress_msg}", end="", flush=True)
print() # New line when complete
log_result("โ
Processing completed!")
Interactive Debugging
For interactive debugging sessions:
from log_candy import input_debug
# Interactive debugging with colored prompts
user_name = input_debug("๐ค Enter your name for testing: ")
user_age = input_debug(f"๐ Enter age for {user_name}: ")
log_result(f"โ
Test user created: {user_name}, age {user_age}")
# Debug complex objects interactively
debug_data = {"name": user_name, "age": int(user_age), "test_session": True}
confirm = input_debug(f"๐ Debug this data? {debug_data} (y/n): ")
if confirm.lower() == 'y':
log_debug(debug_data)
๐ฏ Real-World Use Cases
Web Application Debugging
from log_candy import *
# API endpoint logging
@app.route('/api/users/<user_id>')
def get_user(user_id):
log_info(f"๐ API Request: GET /api/users/{user_id}")
try:
# Database query
user_data = database.get_user(user_id)
log_debug(f"๐ Query result: {user_data}")
if user_data:
log_result(f"โ
User found: {user_data['name']}")
return jsonify(user_data)
else:
log_warning(f"โ ๏ธ User not found: {user_id}")
return jsonify({"error": "User not found"}), 404
except Exception as e:
log_error(f"๐ฅ Database error: {e}")
return jsonify({"error": "Internal server error"}), 500
Data Science Pipeline
import pandas as pd
from log_candy import *
def analyze_dataset(file_path):
set_log_level('INFO') # Hide debug in production
log_info(f"๐ Loading dataset: {file_path}")
df = pd.read_csv(file_path)
# Data exploration
dataset_info = {
"rows": len(df),
"columns": len(df.columns),
"memory_usage": f"{df.memory_usage(deep=True).sum() / 1024**2:.2f} MB",
"null_values": df.isnull().sum().sum()
}
log_debug(dataset_info)
if dataset_info["null_values"] > 0:
log_warning(f"โ ๏ธ Found {dataset_info['null_values']} null values")
# Analysis results
results = {
"mean_age": df['age'].mean(),
"total_revenue": df['revenue'].sum(),
"top_categories": df['category'].value_counts().head(3).to_dict()
}
log_result(results)
return results
DevOps & Monitoring
from log_candy import *
import psutil
import requests
def system_health_check():
log_info("๐ Starting system health check...")
# System resources
system_stats = {
"cpu_percent": psutil.cpu_percent(interval=1),
"memory_percent": psutil.virtual_memory().percent,
"disk_percent": psutil.disk_usage('/').percent
}
log_debug(system_stats)
# Health thresholds
if system_stats["cpu_percent"] > 80:
log_error(f"๐จ High CPU usage: {system_stats['cpu_percent']:.1f}%")
elif system_stats["cpu_percent"] > 60:
log_warning(f"โ ๏ธ Elevated CPU usage: {system_stats['cpu_percent']:.1f}%")
else:
log_info(f"โ
CPU usage normal: {system_stats['cpu_percent']:.1f}%")
# Service connectivity
services = [
{"name": "Database", "url": "http://db.internal:5432"},
{"name": "Redis", "url": "http://cache.internal:6379"},
{"name": "API Gateway", "url": "http://api.internal:8080/health"}
]
for service in services:
try:
response = requests.get(service["url"], timeout=5)
if response.status_code == 200:
log_result(f"โ
{service['name']}: Healthy")
else:
log_warning(f"โ ๏ธ {service['name']}: Status {response.status_code}")
except Exception as e:
log_error(f"๐ฅ {service['name']}: Connection failed - {e}")
๐ Complete API Reference
Core Logging Functions
| Function | Description | Example |
|---|---|---|
log_debug(message) |
Debug-level logging (purple) | log_debug("Variable state: x=5") |
log_info(message) |
Info-level logging (blue) | log_info("Process started") |
log_result(message) |
Result logging (green) | log_result("Task completed") |
log_warning(message) |
Warning logging (yellow) | log_warning("Low memory") |
log_error(message) |
Error logging (red) | log_error("Connection failed") |
Configuration Functions
| Function | Parameters | Description |
|---|---|---|
set_log_level(level) |
level: str |
Set minimum log level ('DEBUG', 'INFO', 'RESULT', 'WARNING', 'ERROR') |
get_log_level() |
None | Get current log level as string |
set_compact_formatting(enabled, threshold) |
enabled: bool, threshold: int |
Configure object formatting |
get_formatting_settings() |
None | Get current formatting configuration |
Special Functions
| Function | Parameters | Description |
|---|---|---|
tqdm_info(message) |
message: Any |
Returns formatted info message for progress bars |
input_debug(message) |
message: Any |
Interactive input with debug-style prompt |
Constants
| Constant | Description |
|---|---|
LOG_LEVELS |
Dictionary mapping level names to numeric values |
๐ง Requirements & Dependencies
- Python: 3.6 or higher
- Dependencies:
tqdm==4.66.4(for progress bar integration)
๐ฎ Getting Started Examples
Want to see all features in action? Create a test file and try these examples:
# test_log_candy.py
from log_candy import *
def demo_basic_features():
"""Try all the basic features of Log Candy"""
# Test all log levels
log_debug("๐ง Debug: Checking variable states")
log_info("๐ Info: Process started")
log_result("โ
Result: Task completed successfully")
log_warning("โ ๏ธ Warning: Memory usage high")
log_error("๐ฅ Error: Connection failed")
# Test different object types
log_info("Simple string")
log_debug({"user": "Alice", "score": 95, "active": True})
log_result([1, 2, 3, "success", {"nested": "data"}])
# Test log level control
print("\n๐๏ธ Testing log level control:")
set_log_level('WARNING')
log_debug("This debug won't show")
log_info("This info won't show")
log_warning("This warning will show")
# Reset to show all
set_log_level('DEBUG')
log_info("Back to showing all levels!")
if __name__ == "__main__":
demo_basic_features()
Run it with:
python test_log_candy.py
The examples cover:
- ๐ฏ All 5 log levels with real-world examples
- ๐ฆ Different object types (strings, numbers, lists, dicts, custom objects)
- ๐๏ธ Log level filtering demonstration
- ๐จ Object formatting examples
๐ค Contributing
We welcome contributions! Whether it's bug fixes, new features, documentation improvements, or examples, your help makes Log Candy better for everyone.
๐ Ways to Contribute
- ๐ Bug Reports: Found an issue? Open an issue
- ๐ก Feature Requests: Have an idea? We'd love to hear it!
- ๐ Documentation: Help improve our docs and examples
- ๐ง Code: Submit pull requests for bug fixes or new features
- ๐งช Testing: Help us test across different Python versions and environments
๐ฏ What We're Looking For
- ๐ New color themes or customization options
- ๐ Integration with popular logging frameworks
- ๐ง Performance improvements
- ๐ฑ Better formatting for specific object types
- ๐งช More comprehensive tests
- ๐ Usage examples and tutorials
๐ Acknowledgements
- Contributors: Thank you to all contributors who help make Log Candy better!
- Community: Special thanks to everyone who uses Log Candy and provides feedback
- Inspiration: Built with love for the Python community and beautiful terminal output
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Show Your Support
If Log Candy helps make your debugging more delightful, consider:
- โญ Starring the repository on GitHub
- ๐ฆ Sharing with your developer friends
- ๐ Contributing to the project
- ๐ Writing about your experience with Log Candy
Happy Logging! ๐ญโจ
Made with โค๏ธ by Sabino Roccotelli
Project details
Release history Release notifications | RSS feed
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 log_candy-0.1.4.tar.gz.
File metadata
- Download URL: log_candy-0.1.4.tar.gz
- Upload date:
- Size: 15.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2663e3f7200e5740cfbf3cc1ba163ef7b53deb9dfa50e6362d2c0c0e436c2172
|
|
| MD5 |
f60607a2fcf690376ab38044bb27c28e
|
|
| BLAKE2b-256 |
7fa744d167fbccee9ab5048949ed1a9c997e09d97164e170e8db82bb1b178c4f
|
File details
Details for the file log_candy-0.1.4-py3-none-any.whl.
File metadata
- Download URL: log_candy-0.1.4-py3-none-any.whl
- Upload date:
- Size: 10.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7df0cfa715515676c0f3b1d558fedc71cd3a8cb57b31231515d966d666de4304
|
|
| MD5 |
a91d1e23951e01f2519ad6dced9dae01
|
|
| BLAKE2b-256 |
f78a951d5a7e0174e29544e6977badd7becfede90ace98da9e4d90652752e5c2
|