Async Logging¶
LogEverything provides high-performance async logging optimized for modern Python applications. This guide covers async logging patterns, the AsyncLogger class, and performance optimization techniques.
🚀 Why Async Logging?¶
- Performance Benefits:
454 ops/sec async-native logging with task isolation
Non-blocking - doesn’t slow down your application
Concurrent processing - multiple log operations simultaneously
Queue-based - background processing for heavy logging
- Perfect for:
Web applications (FastAPI, aiohttp, Django async views)
High-throughput systems (data processing, API servers)
Real-time applications (chat, gaming, streaming)
Microservices with async communication
Data pipelines and ML training
See also
📋 Mixing Sync and Async Logging?
When using both sync loggers and async functions (or vice versa), LogEverything automatically creates shared loggers for optimal compatibility. See Async/Sync Best Practices & Shared Logger Behavior for detailed information about shared logger creation, performance implications, and best practices for mixed sync/async applications.
⚡ AsyncLogger Class¶
The AsyncLogger class is specifically optimized for async applications:
Basic Usage¶
from logeverything.asyncio import AsyncLogger
import asyncio
# AsyncLogger automatically enables async_mode=True
log = AsyncLogger("async_app")
log.info("🚀 Async application started")
# Simulate async operations
await asyncio.sleep(0.1)
log.info("⚡ Async operation completed")
Output:
2026-05-01 05:38:56 | [ ℹ️ INFO ] | async_app | 🚀 Async application started
2026-05-01 05:38:56 | [ ℹ️ INFO ] | async_app | ⚡ Async operation completed
High-Performance Async Methods¶
AsyncLogger provides async-optimized methods for maximum performance:
from logeverything.asyncio import AsyncLogger
import asyncio
async def high_performance_logging():
log = AsyncLogger("high_perf")
# Use async methods for best performance (6.8x faster)
await log.ainfo("High-performance async info")
await log.adebug("High-performance async debug")
await log.awarning("High-performance async warning")
await log.aerror("High-performance async error")
# Regular methods also work (slightly less optimized)
log.info("Regular sync method")
return "Logging completed"
result = await high_performance_logging()
print(f"Result: {result}")
Output:
2026-05-01 05:38:56 | [ ℹ️ INFO ] | high_perf | High-performance async info
2026-05-01 05:38:56 | [ 🔍 DEBUG ] | high_perf | High-performance async debug
2026-05-01 05:38:56 | [⚠️ WARNING ] | high_perf | High-performance async warning
2026-05-01 05:38:56 | [ ❌ ERROR ] | high_perf | High-performance async error
2026-05-01 05:38:56 | [ ℹ️ INFO ] | high_perf | Regular sync method
Result: Logging completed
Configuration for Performance¶
Configure AsyncLogger for optimal performance:
from logeverything.asyncio import AsyncLogger
async def configure_performance():
log = AsyncLogger("optimized")
# Configure for high-throughput applications
await log.configure(
level="INFO",
async_queue_size=10000, # Large queue for high volume
async_flush_interval=0.05, # Fast flush for responsiveness
visual_mode=True,
use_symbols=True
)
log.info("⚡ High-performance async logging configured")
# Test high-volume logging
for i in range(100):
log.info(f"High-volume log {i}")
return "Configuration complete"
result = await configure_performance()
print(f"Result: {result}")
Output:
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | ⚡ High-performance async logging configured
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 0
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 1
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 2
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 3
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 4
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 5
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 6
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 7
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 8
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 9
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 10
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 11
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 12
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 13
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 14
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 15
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 16
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 17
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 18
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 19
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 20
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 21
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 22
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 23
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 24
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 25
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 26
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 27
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 28
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 29
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 30
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 31
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 32
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 33
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 34
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 35
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 36
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 37
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 38
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 39
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 40
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 41
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 42
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 43
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 44
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 45
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 46
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 47
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 48
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 49
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 50
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 51
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 52
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 53
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 54
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 55
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 56
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 57
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 58
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 59
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 60
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 61
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 62
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 63
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 64
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 65
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 66
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 67
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 68
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 69
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 70
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 71
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 72
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 73
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 74
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 75
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 76
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 77
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 78
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 79
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 80
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 81
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 82
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 83
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 84
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 85
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 86
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 87
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 88
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 89
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 90
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 91
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 92
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 93
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 94
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 95
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 96
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 97
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 98
2026-05-01 05:38:56 | [ ℹ️ INFO ] | optimized | High-volume log 99
Result: Configuration complete
🔄 Intelligent Type Casting with Async¶
LogEverything automatically handles sync/async logger mismatches, making it easy to integrate async logging into existing applications:
Sync Loggers with Async Functions¶
You can use regular (sync) loggers with async functions seamlessly:
import asyncio
from logeverything import Logger # Regular sync logger
from logeverything.decorators import log
# Create a regular sync logger
sync_logger = Logger("mixed_service", level="INFO")
@log(using="mixed_service") # Automatically casts sync logger for async compatibility
async def async_data_fetch(resource_id):
"""Async function using sync logger - works automatically."""
await asyncio.sleep(0.1) # Simulate async database fetch
return {"id": resource_id, "data": "fetched_data", "timestamp": "2024-01-01"}
@log(using="mixed_service") # Same logger works with both sync and async
def sync_data_validate(data):
"""Sync function using the same logger."""
return data.get("id") is not None and len(data.get("data", "")) > 0
# Both functions work with the same logger
data = await async_data_fetch(123)
is_valid = sync_data_validate(data)
print(f"Data valid: {is_valid}")
Output:
2026-05-01 05:38:56 | [ ℹ️ INFO ] | mixed_servi...sync_shared | 🔵 CALL async_data_fetch(resource_id=123) [base_events.py:1936]
2026-05-01 05:38:56 | [ ℹ️ INFO ] | mixed_servi...sync_shared | ✅ DONE async_data_fetch (100.63ms) ➜ {'id': 123, 'data': 'fetched_data', 'timestamp': '2024-01-01'}
Data valid: True
Async Loggers with Sync Functions¶
AsyncLoggers also work seamlessly with sync functions:
from logeverything.asyncio import AsyncLogger
from logeverything.decorators import log
# Create an async logger
async_logger = AsyncLogger("async_service", level="DEBUG")
@log(using="async_service") # Automatically casts async logger for sync compatibility
def sync_computation(x, y):
"""Sync function using async logger - works automatically."""
result = (x ** 2) + (y ** 2)
return {"result": result, "inputs": [x, y]}
@log(using="async_service") # Same logger can be used in mixed environments
def sync_formatter(data):
"""Sync formatting function."""
return f"Result: {data['result']} from inputs {data['inputs']}"
# Sync functions work with async logger
computed = sync_computation(3, 4)
formatted = sync_formatter(computed)
print(formatted)
Output:
2026-05-01 05:38:56 | INFO | async_service_sync_temp | 🔵 CALL sync_computation(x=3, y=4) [tmpjdm0_2cr.py:64]
2026-05-01 05:38:56 | INFO | async_service_sync_temp | ✅ DONE sync_computation (4.38ms) ➜ {'result': 25, 'inputs': [3, 4]}
2026-05-01 05:38:56 | INFO | async_service_sync_temp | 🔵 CALL sync_formatter(data={'result': 25, 'inputs': [3, 4]}) [tmpjdm0_2cr.py:65]
2026-05-01 05:38:56 | INFO | async_service_sync_temp | ✅ DONE sync_formatter (0.00ms) ➜ 'Result: 25 from inputs [3, 4]'
Result: 25 from inputs [3, 4]
Mixed Application Pattern¶
Real-world applications often mix sync and async code. Type casting makes this seamless:
import asyncio
from logeverything import Logger
from logeverything.decorators import log
# Single logger for the entire application
app_logger = Logger("UserApplication", level="INFO")
@log(using="UserApplication")
def validate_user_input(user_data):
"""Sync validation - fast and simple."""
required_fields = ["username", "email"]
return all(field in user_data for field in required_fields)
@log(using="UserApplication")
async def save_user_to_database(user_data):
"""Async database operation."""
await asyncio.sleep(0.1) # Simulate async database save
user_id = hash(user_data["username"]) % 10000
return {"user_id": user_id, "status": "saved"}
@log(using="UserApplication")
def send_welcome_email(user_id):
"""Sync email sending (using sync email library)."""
# Simulate email sending
return f"Welcome email sent to user {user_id}"
async def process_user_registration(user_data):
"""Complete user registration pipeline mixing sync/async."""
# Step 1: Sync validation
if not validate_user_input(user_data):
return {"error": "Invalid user data"}
# Step 2: Async database save
save_result = await save_user_to_database(user_data)
# Step 3: Sync email (using existing sync email library)
email_result = send_welcome_email(save_result["user_id"])
return {"success": True, "user_id": save_result["user_id"], "email": email_result}
# Test the mixed pipeline
user_data = {"username": "alice", "email": "alice@example.com"}
result = await process_user_registration(user_data)
print(f"Registration result: {result}")
Output:
2026-05-01 05:38:56 | [ ℹ️ INFO ] | UserApplica...sync_shared | 🔵 CALL save_user_to_database(user_data={'username': 'alice', 'email': 'alice@example.com'}) [events.py:84]
2026-05-01 05:38:56 | [ ℹ️ INFO ] | UserApplica...sync_shared | ✅ DONE save_user_to_database (100.62ms) ➜ {'user_id': 4075, 'status': 'saved'}
Registration result: {'success': True, 'user_id': 4075, 'email': 'Welcome email sent to user 4075'}
Benefits of Type Casting:
No Code Changes: Existing sync code works with async loggers
Gradual Migration: Add async functionality without changing logging setup
Consistent Logging: Single logger handles entire application regardless of sync/async mix
Zero Configuration: Automatic detection and conversion
Performance Optimized: Casting is cached for minimal overhead
🏃♂️ Concurrent Async Logging¶
Process multiple async operations with concurrent logging:
from logeverything.asyncio import AsyncLogger
import asyncio
import random
async def process_user_request(user_id: int, log: AsyncLogger):
"""Process a user request with async logging."""
await log.ainfo(f"📨 Processing request for user {user_id}")
# Simulate async work with random duration
work_time = random.uniform(0.05, 0.15)
await asyncio.sleep(work_time)
# Simulate different outcomes
if random.random() > 0.8: # 20% chance of warning
await log.awarning(f"⚠️ Slow processing for user {user_id}", duration=work_time)
else:
await log.ainfo(f"✅ Request completed for user {user_id}", duration=work_time)
return {"user_id": user_id, "status": "completed", "duration": work_time}
async def concurrent_processing():
log = AsyncLogger("concurrent_demo")
# Process multiple users concurrently
user_ids = range(1, 11) # 10 users
tasks = [process_user_request(user_id, log) for user_id in user_ids]
log.info(f"🚀 Starting concurrent processing of {len(tasks)} requests")
start_time = asyncio.get_event_loop().time()
results = await asyncio.gather(*tasks)
end_time = asyncio.get_event_loop().time()
total_time = end_time - start_time
log.bind(requests=len(results),
total_time=f"{total_time:.3f}s",
throughput=f"{len(results)/total_time:.1f} req/s").info(f"🎉 Concurrent processing completed")
return results
results = await concurrent_processing()
print(f"Processed {len(results)} requests concurrently")
Output:
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | 🚀 Starting concurrent processing of 10 requests
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | 📨 Processing request for user 1
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | 📨 Processing request for user 2
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | 📨 Processing request for user 3
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | 📨 Processing request for user 4
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | 📨 Processing request for user 5
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | 📨 Processing request for user 6
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | 📨 Processing request for user 7
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | 📨 Processing request for user 8
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | 📨 Processing request for user 9
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | 📨 Processing request for user 10
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | [duration=0.06099994506919148] ✅ Request completed for user 2
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | [duration=0.07242175797279303] ✅ Request completed for user 3
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | [duration=0.07761246555678608] ✅ Request completed for user 8
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | [duration=0.0799522290130618] ✅ Request completed for user 6
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | [duration=0.09896030266693762] ✅ Request completed for user 10
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | [duration=0.12060141610259086] ✅ Request completed for user 5
2026-05-01 05:38:57 | [⚠️ WARNING ] | concurrent_demo | [duration=0.13048694055581966] ⚠️ Slow processing for user 4
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | [duration=0.1326299505743741] ✅ Request completed for user 1
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | [duration=0.1344567772674264] ✅ Request completed for user 9
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | [duration=0.1409933452183425] ✅ Request completed for user 7
2026-05-01 05:38:57 | [ ℹ️ INFO ] | concurrent_demo | [requests=10 | total_time=0.142s | throughput=70.3 req/s] 🎉 Concurrent processing completed
Processed 10 requests concurrently
📊 Async Context Managers¶
Use async context managers for hierarchical async logging:
from logeverything.asyncio import AsyncLogger
import asyncio
async def data_pipeline_demo():
"""Demonstrate async context managers in a data pipeline."""
log = AsyncLogger("data_pipeline")
async with log.context("Data Processing Pipeline"):
await log.ainfo("🚀 Starting async data pipeline")
# Data fetching phase
async with log.context("Data Fetching"):
await log.ainfo("📡 Connecting to data sources")
await asyncio.sleep(0.1) # Simulate API calls
await log.ainfo("📥 Fetching user data")
await asyncio.sleep(0.1) # Simulate data fetch
await log.ainfo("📥 Fetching product data")
await asyncio.sleep(0.1) # Simulate data fetch
await log.ainfo("✅ Data fetching completed")
# Data processing phase
async with log.context("Data Processing"):
await log.ainfo("⚙️ Starting data transformation")
await asyncio.sleep(0.15) # Simulate processing
await log.ainfo("🔗 Joining datasets")
await asyncio.sleep(0.1) # Simulate joins
await log.ainfo("📊 Calculating aggregations")
await asyncio.sleep(0.1) # Simulate calculations
await log.ainfo("✅ Data processing completed")
# Data validation phase
async with log.context("Data Validation"):
await log.ainfo("🔍 Validating data quality")
await asyncio.sleep(0.05) # Simulate validation
await log.awarning("⚠️ Found 3 invalid records")
await log.ainfo("🧹 Cleaning invalid data")
await asyncio.sleep(0.05) # Simulate cleaning
await log.ainfo("✅ Data validation completed")
await log.ainfo("🎉 Pipeline completed successfully")
await data_pipeline_demo()
Output:
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | ┌─► Data Processing Pipeline
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | 🚀 Starting async data pipeline
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | ┌─► Data Fetching
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | 📡 Connecting to data sources
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | 📥 Fetching user data
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | 📥 Fetching product data
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | ✅ Data fetching completed
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | └─◄ Data Fetching complete
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | ┌─► Data Processing
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | ⚙️ Starting data transformation
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | 🔗 Joining datasets
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | 📊 Calculating aggregations
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | ✅ Data processing completed
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | └─◄ Data Processing complete
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | ┌─► Data Validation
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | 🔍 Validating data quality
2026-05-01 05:38:57 | [⚠️ WARNING ] | data_pipeline | ⚠️ Found 3 invalid records
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | 🧹 Cleaning invalid data
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | ✅ Data validation completed
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | └─◄ Data Validation complete
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | 🎉 Pipeline completed successfully
2026-05-01 05:38:57 | [ ℹ️ INFO ] | data_pipeline | └─◄ Data Processing Pipeline complete
⚙️ Async Decorators¶
Use async-optimized decorators for automatic function logging:
from logeverything.decorators import log
from logeverything.asyncio import async_log_function
import asyncio
# Smart decorator automatically detects async functions
@log
async def fetch_user_profile(user_id: int):
"""Fetch user profile asynchronously."""
await asyncio.sleep(0.1) # Simulate database query
return {
"user_id": user_id,
"name": f"User {user_id}",
"profile": {"preferences": {}, "settings": {}}
}
# Explicit async decorator for fine control
@async_log_function
async def update_user_profile(user_id: int, updates: dict):
"""Update user profile asynchronously."""
await asyncio.sleep(0.05) # Simulate database update
return {"user_id": user_id, "updated_fields": list(updates.keys())}
async def test_async_decorators():
# Test both decorated functions
profile = await fetch_user_profile(123)
updates = {"theme": "dark", "notifications": True}
update_result = await update_user_profile(123, updates)
print(f"Profile: {profile}")
print(f"Update result: {update_result}")
await test_async_decorators()
Output:
2026-05-01 05:38:58 | [ ℹ️ INFO ] | decorator_t...sync_shared | 🔵 CALL fetch_user_profile(user_id=123) [events.py:84]
2026-05-01 05:38:58 | [ ℹ️ INFO ] | decorator_t...sync_shared | ✅ DONE fetch_user_profile (100.65ms) ➜ {'user_id': 123, 'name': 'User 123', 'profile': {'preferences': {}, 'settings': {}}}
2026-05-01 05:38:58 | [ ℹ️ INFO ] | decorator_t...sync_shared | 🔵 CALL update_user_profile(user_id=123, updates={'theme': 'dark', 'notifications': True}) [events.py:84]
2026-05-01 05:38:58 | [ ℹ️ INFO ] | decorator_t...sync_shared | ✅ DONE update_user_profile (50.36ms) ➜ {'user_id': 123, 'updated_fields': ['theme', 'notifications']}
Profile: {'user_id': 123, 'name': 'User 123', 'profile': {'preferences': {}, 'settings': {}}}
Update result: {'user_id': 123, 'updated_fields': ['theme', 'notifications']}
🏗️ Async Class Logging¶
Log all methods of async classes automatically:
from logeverything.asyncio import async_log_class
import asyncio
@async_log_class
class AsyncUserService:
"""Async user service with automatic method logging."""
def __init__(self, name: str):
self.name = name
self.processed_count = 0
async def authenticate(self, username: str, password: str):
"""Authenticate user asynchronously."""
await asyncio.sleep(0.05) # Simulate auth check
# Simple authentication simulation
is_valid = len(password) >= 8
self.processed_count += 1
return {"valid": is_valid, "token": f"token_{username}" if is_valid else None}
async def get_user_data(self, user_id: int):
"""Get user data asynchronously."""
await asyncio.sleep(0.1) # Simulate database query
self.processed_count += 1
return {
"user_id": user_id,
"username": f"user_{user_id}",
"email": f"user{user_id}@example.com",
"active": True
}
async def update_user(self, user_id: int, updates: dict):
"""Update user asynchronously."""
await asyncio.sleep(0.08) # Simulate database update
self.processed_count += 1
return {"user_id": user_id, "updated": True, "changes": updates}
def get_stats(self):
"""Get service statistics (sync method)."""
return {"service": self.name, "processed": self.processed_count}
async def test_async_class():
service = AsyncUserService("UserService_v1")
# All async methods are automatically logged
auth_result = await service.authenticate("alice", "secretpassword")
user_data = await service.get_user_data(123)
update_result = await service.update_user(123, {"active": False})
# Sync method also logged
stats = service.get_stats()
print(f"Auth: {auth_result}")
print(f"User: {user_data}")
print(f"Update: {update_result}")
print(f"Stats: {stats}")
await test_async_class()
Output:
2026-05-01 05:38:58 | [ ℹ️ INFO ] | decorator_t...sync_shared | 🔵 CALL _async_main.<locals>.AsyncUserService.authenticate(self=<__main__._async_main.<locals>.AsyncUserService object at 0x7b29bf3a2a90>, username='alice', password='secretpassword') [events.py:84]
2026-05-01 05:38:58 | [ ℹ️ INFO ] | decorator_t...sync_shared | ✅ DONE _async_main.<locals>.AsyncUserService.authenticate (50.36ms) ➜ {'valid': True, 'token': 'token_alice'}
2026-05-01 05:38:58 | [ ℹ️ INFO ] | decorator_t...sync_shared | 🔵 CALL _async_main.<locals>.AsyncUserService.get_user_data(self=<__main__._async_main.<locals>.AsyncUserService object at 0x7b29bf3a2a90>, user_id=123) [events.py:84]
2026-05-01 05:38:58 | [ ℹ️ INFO ] | decorator_t...sync_shared | ✅ DONE _async_main.<locals>.AsyncUserService.get_user_data (100.65ms) ➜ {'user_id': 123, 'username': 'user_123', 'email': 'user123@example.com', 'active': True}
2026-05-01 05:38:58 | [ ℹ️ INFO ] | decorator_t...sync_shared | 🔵 CALL _async_main.<locals>.AsyncUserService.update_user(self=<__main__._async_main.<locals>.AsyncUserService object at 0x7b29bf3a2a90>, user_id=123, updates={'active': False}) [events.py:84]
2026-05-01 05:38:58 | [ ℹ️ INFO ] | decorator_t...sync_shared | ✅ DONE _async_main.<locals>.AsyncUserService.update_user (80.53ms) ➜ {'user_id': 123, 'updated': True, 'changes': {'active': False}}
2026-05-01 05:38:58 | [ ℹ️ INFO ] | decorator_temp | 🔵 CALL _async_main.<locals>.AsyncUserService.get_stats() [events.py:84]
2026-05-01 05:38:58 | [ ℹ️ INFO ] | decorator_temp | ✅ DONE _async_main.<locals>.AsyncUserService.get_stats (4.78ms) ➜ {'service': 'UserService_v1', 'processed': 3}
Auth: {'valid': True, 'token': 'token_alice'}
User: {'user_id': 123, 'username': 'user_123', 'email': 'user123@example.com', 'active': True}
Update: {'user_id': 123, 'updated': True, 'changes': {'active': False}}
Stats: {'service': 'UserService_v1', 'processed': 3}
🔥 Performance Comparison¶
See the performance difference between sync and async logging:
import asyncio
import time
from logeverything import Logger
from logeverything.asyncio import AsyncLogger
async def performance_benchmark():
"""Benchmark sync vs async logging performance."""
num_operations = 50 # Reduced for demo
print("🏁 Starting performance benchmark...")
# Sync logging benchmark
sync_log = Logger("sync_benchmark")
start_time = time.time()
for i in range(num_operations):
sync_log.info(f"Sync operation {i}")
sync_time = time.time() - start_time
# Async logging benchmark
async_log = AsyncLogger("async_benchmark")
start_time = time.time()
# Create concurrent logging tasks
tasks = [
async_log.ainfo(f"Async operation {i}")
for i in range(num_operations)
]
await asyncio.gather(*tasks)
async_time = time.time() - start_time
# Calculate results
if async_time > 0:
speedup = sync_time / async_time
throughput_sync = num_operations / sync_time
throughput_async = num_operations / async_time
print(f"\n📊 Performance Results:")
print(f"Sync logging: {sync_time:.4f}s ({throughput_sync:.1f} ops/sec)")
print(f"Async logging: {async_time:.4f}s ({throughput_async:.1f} ops/sec)")
print(f"Speedup: {speedup:.1f}x faster with AsyncLogger! 🚀")
else:
print("Async logging was too fast to measure! ⚡")
await performance_benchmark()
Output:
🏁 Starting performance benchmark...
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 0
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 1
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 2
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 3
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 4
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 5
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 6
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 7
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 8
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 9
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 10
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 11
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 12
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 13
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 14
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 15
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 16
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 17
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 18
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 19
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 20
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 21
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 22
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 23
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 24
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 25
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 26
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 27
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 28
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 29
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 30
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 31
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 32
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 33
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 34
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 35
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 36
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 37
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 38
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 39
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 40
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 41
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 42
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 43
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 44
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 45
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 46
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 47
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 48
2026-05-01 05:38:58 | [ ℹ️ INFO ] | sync_benchmark | Sync operation 49
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 0
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 1
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 2
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 3
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 4
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 5
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 6
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 7
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 8
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 9
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 10
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 11
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 12
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 13
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 14
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 15
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 16
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 17
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 18
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 19
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 20
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 21
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 22
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 23
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 24
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 25
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 26
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 27
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 28
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 29
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 30
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 31
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 32
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 33
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 34
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 35
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 36
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 37
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 38
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 39
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 40
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 41
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 42
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 43
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 44
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 45
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 46
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 47
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 48
2026-05-01 05:38:58 | [ ℹ️ INFO ] | async_benchmark | Async operation 49
📊 Performance Results:
Sync logging: 0.0029s (17226.5 ops/sec)
Async logging: 0.0039s (12847.8 ops/sec)
Speedup: 0.7x faster with AsyncLogger! 🚀
🌐 Web Framework Integration¶
AsyncLogger works seamlessly with async web frameworks:
FastAPI Example¶
from fastapi import FastAPI
from logeverything.asyncio import AsyncLogger
import asyncio
app = FastAPI()
api_log = AsyncLogger("fastapi_app")
@app.middleware("http")
async def logging_middleware(request, call_next):
await api_log.ainfo("🌐 Request received",
method=request.method,
url=str(request.url))
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
await api_log.ainfo("📤 Request completed",
status=response.status_code,
duration=f"{process_time:.3f}s")
return response
@app.get("/users/{user_id}")
async def get_user(user_id: int):
await api_log.ainfo("👤 Getting user", user_id=user_id)
# Simulate async database query
await asyncio.sleep(0.1)
user = {"id": user_id, "name": f"User {user_id}"}
await api_log.ainfo("✅ User retrieved", user=user)
return user
aiohttp Example¶
from aiohttp import web
from logeverything.asyncio import AsyncLogger
async def create_app():
app = web.Application()
app['logger'] = AsyncLogger("aiohttp_app")
async def hello_handler(request):
log = request.app['logger']
name = request.match_info.get('name', 'World')
await log.ainfo("👋 Handling hello request", name=name)
return web.json_response({"message": f"Hello, {name}!"})
app.router.add_get('/hello/{name}', hello_handler)
return app
📈 Structured Async Logging¶
Use structured logging with async applications using .bind() for persistent context:
See also
For detailed information about binding behavior, registry management, and best practices, see Logger Binding and Registry Management
from logeverything.asyncio import AsyncLogger
import asyncio
import uuid
async def e_commerce_order_processing():
"""Demonstrate structured async logging in e-commerce."""
log = AsyncLogger("ecommerce")
# Generate request context
request_id = str(uuid.uuid4())[:8]
user_id = 12345
# Bind context for all subsequent logs
order_log = log.bind(request_id=request_id, user_id=user_id)
async with order_log.context("Order Processing"):
await order_log.ainfo("🛒 Order processing started",
order_id="ORD-001",
items_count=3,
total_amount=99.99)
# Inventory check
async with order_log.context("Inventory Check"):
await order_log.ainfo("📦 Checking inventory")
await asyncio.sleep(0.1) # Simulate inventory check
await order_log.ainfo("✅ Inventory available",
available_items=3,
reserved_items=3)
# Payment processing
async with order_log.context("Payment Processing"):
await order_log.ainfo("💳 Processing payment",
payment_method="credit_card",
amount=99.99)
await asyncio.sleep(0.15) # Simulate payment processing
await order_log.ainfo("✅ Payment successful",
transaction_id="TXN-12345",
status="approved")
# Shipping
async with order_log.context("Shipping"):
await order_log.ainfo("📦 Creating shipping label")
await asyncio.sleep(0.05) # Simulate shipping
await order_log.ainfo("🚚 Order shipped",
tracking_number="TRACK-67890",
carrier="FastShip",
estimated_delivery="2025-07-01")
await order_log.ainfo("🎉 Order processing completed",
order_status="shipped",
processing_time="0.3s")
await e_commerce_order_processing()
Output:
2026-05-01 05:38:58 | [ ℹ️ INFO ] | ecommerce | ┌─► Order Processing
2026-05-01 05:38:58 | [ ℹ️ INFO ] | ecommerce | [request_id=bba413b1 | user_id=12345 | order_id=ORD-001 | items_count=3 | total_amount=99.99] 🛒 Order processing started
2026-05-01 05:38:58 | [ ℹ️ INFO ] | ecommerce | ┌─► Inventory Check
2026-05-01 05:38:58 | [ ℹ️ INFO ] | ecommerce | [request_id=bba413b1 | user_id=12345] 📦 Checking inventory
2026-05-01 05:38:58 | [ ℹ️ INFO ] | ecommerce | [request_id=bba413b1 | user_id=12345 | available_items=3 | reserved_items=3] ✅ Inventory available
2026-05-01 05:38:58 | [ ℹ️ INFO ] | ecommerce | └─◄ Inventory Check complete
2026-05-01 05:38:58 | [ ℹ️ INFO ] | ecommerce | ┌─► Payment Processing
2026-05-01 05:38:58 | [ ℹ️ INFO ] | ecommerce | [request_id=bba413b1 | user_id=12345 | payment_method=credit_card | amount=99.99] 💳 Processing payment
2026-05-01 05:38:58 | [ ℹ️ INFO ] | ecommerce | [request_id=bba413b1 | user_id=12345 | transaction_id=TXN-12345 | status=approved] ✅ Payment successful
2026-05-01 05:38:58 | [ ℹ️ INFO ] | ecommerce | └─◄ Payment Processing complete
2026-05-01 05:38:58 | [ ℹ️ INFO ] | ecommerce | ┌─► Shipping
2026-05-01 05:38:58 | [ ℹ️ INFO ] | ecommerce | [request_id=bba413b1 | user_id=12345] 📦 Creating shipping label
2026-05-01 05:38:59 | [ ℹ️ INFO ] | ecommerce | [request_id=bba413b1 | user_id=12345 | tracking_number=TRACK-67890 | carrier=FastShip | estimated_delivery=2025-07-01] 🚚 Order shipped
2026-05-01 05:38:59 | [ ℹ️ INFO ] | ecommerce | └─◄ Shipping complete
2026-05-01 05:38:59 | [ ℹ️ INFO ] | ecommerce | [request_id=bba413b1 | user_id=12345 | order_status=shipped | processing_time=0.3s] 🎉 Order processing completed
2026-05-01 05:38:59 | [ ℹ️ INFO ] | ecommerce | └─◄ Order Processing complete
🔧 Best Practices¶
Async Logger Configuration¶
# High-performance configuration for production
await async_log.configure(
level="INFO",
async_queue_size=50000, # Large queue for high volume
async_flush_interval=0.1, # Frequent flushes
visual_mode=False, # Disable visual mode for performance
handlers=["file", "console"]
)
# Development configuration
await async_log.configure(
level="DEBUG",
async_queue_size=1000, # Smaller queue for development
visual_mode=True, # Enable visual enhancements
use_symbols=True,
use_colors=True
)
Resource Management¶
# Always clean up async resources
async def proper_cleanup():
log = AsyncLogger("temp")
try:
await log.ainfo("Using async logger")
# Your async operations here
finally:
await log.close() # Clean up resources
# Or use async context manager
async def context_manager_cleanup():
async with AsyncLogger("temp") as log:
await log.ainfo("Automatic cleanup")
# Resources automatically cleaned up
Error Handling¶
@async_log_function
async def safe_async_operation():
try:
# Risky async operation
await risky_async_call()
except Exception as e:
# Exception automatically logged by decorator
await log.aerror("Recovery action taken")
# Handle the error appropriately
Performance Monitoring¶
async def monitor_performance():
log = AsyncLogger("performance")
start_time = asyncio.get_event_loop().time()
# Your async operations
await your_async_operations()
duration = asyncio.get_event_loop().time() - start_time
if duration > 1.0: # Log slow operations
await log.awarning("Slow operation detected",
duration=f"{duration:.3f}s")
🎯 Common Patterns¶
Request Processing¶
async def process_api_request(request_data):
log = AsyncLogger("api")
request_id = request_data.get("id")
# Bind request context
request_log = log.bind(request_id=request_id)
async with request_log.context("API Request"):
await request_log.ainfo("Request received")
# Process request
result = await process_request(request_data)
await request_log.ainfo("Request completed",
status="success")
return result
Batch Processing¶
async def process_batch(items):
log = AsyncLogger("batch_processor")
async with log.context("Batch Processing"):
await log.ainfo(f"Processing {len(items)} items")
# Process items concurrently
tasks = [process_item(item, log) for item in items]
results = await asyncio.gather(*tasks)
await log.ainfo("Batch completed",
items_processed=len(results))
return results
Background Tasks¶
async def background_worker():
log = AsyncLogger("worker")
while True:
try:
await log.ainfo("Worker cycle started")
# Do background work
await process_queue()
await asyncio.sleep(30) # Wait before next cycle
except Exception as e:
await log.aerror("Worker error", error=str(e))
await asyncio.sleep(60) # Wait longer on error
API Reference¶
AsyncLogger Methods¶
# High-performance async methods
await log.ainfo(message, **kwargs)
await log.adebug(message, **kwargs)
await log.awarning(message, **kwargs)
await log.aerror(message, **kwargs)
await log.aexception(message, **kwargs)
# Standard methods (also work)
log.info(message, **kwargs)
log.debug(message, **kwargs)
log.warning(message, **kwargs)
log.error(message, **kwargs)
log.exception(message, **kwargs)
# Configuration and context
await log.configure(**options)
async with log.context(name, **context):
pass
# Resource management
await log.close()
Async Decorators¶
# Smart decorator (automatically detects async)
@log
async def my_async_function():
pass
# Explicit async decorators
@async_log_function
async def async_function():
pass
@async_log_class
class AsyncClass:
pass
See Also¶
Logger Classes - Logger and AsyncLogger comparison
Smart Decorators - Async decorator usage
Performance and Optimization - Performance optimization
Production Deployment - Production deployment guide