Logging Configuration
Logging Configuration
The framework integrates a powerful logging system based on loguru, with high performance and an easy API.
Core features
- High performance: loguru-based, with asynchronous writes
- Flexible configuration: config file or code
- Automatic management: rotation, compression and cleanup
- Rich formatting: coloured output and custom formats
- Exception tracing: detailed error info and stack traces
Overview
| Feature | Description | Benefit |
|---|---|---|
| Config file integration | Manage logging from YAML | Easier maintenance and deployment |
| Multiple levels | DEBUG, INFO, WARNING, ERROR, CRITICAL | Precise control of output |
| Automatic rotation | Rotate by size or time | Avoids oversized files |
| Compression | Several compression formats | Saves disk space |
| Async writes | Non-blocking logging | Better performance |
| Custom formats | Flexible format templates | Fits different needs |
Quick Start
Basic Usage
The SDK uses loguru as its logging library:
from loguru import logger
# Basic logging
logger.debug("调试信息")
logger.info("普通信息")
logger.warning("警告信息")
logger.error("错误信息")
logger.critical("严重错误")Config-file Logging (Recommended)
When the service starts, manage logging through the config file; it is easier to maintain and deploy.
Complete Example
# main.py
import asyncio
from simplejrpc.app import ServerApplication
from simplejrpc.response import jsonify
sock_path = "/xxx/app.sock"
config_path = "/xxx/config.yaml"
# Load the config at startup; loguru is configured automatically
app = ServerApplication(socket_path=sock_path, config_path=config_path)
@app.route(name="hello")
async def hello():
return jsonify(data="hello world!", msg="OK")
if __name__ == "__main__":
asyncio.run(app.run())config.yaml Reference
# Logging configuration (required)
logger:
sink: app.log # Output destination (required)
level: DEBUG # Log level
diagnose: false # Emit debug info (e.g. local variables)
enqueue: true # Async logging (recommended)
rotation: "500 MB" # Rotation condition
retention: "1 months" # Retention period
compression: tar # Compression format (tar/zip, etc.)
format: "<green>{time:YYYYMMDD HH:mm:ss}</green> | \
{process.name} | {thread.name} | \
<cyan>{module}</cyan>.<cyan>{function}</cyan>:<cyan>{line}</cyan> | \
<level>{level}</level>: <level>{message}</level>"Options Reference
| Option | Type | Required | Default | Description |
|---|---|---|---|---|
sink | string | ✅ | - | Output target: file path, stdout or stderr |
level | string | ❌ | INFO | Level: TRACE, DEBUG, INFO, SUCCESS, WARNING, ERROR, CRITICAL |
diagnose | boolean | ❌ | false | Emit detailed debug info (local variables, etc.) |
enqueue | boolean | ❌ | false | Async logging for better performance |
rotation | string | ❌ | - | Rotation rule: "500 MB", "1 day", "weekly" |
retention | string | ❌ | - | Retention: "30 days", "1 week" |
compression | string | ❌ | - | Compression: tar, gz, zip, bz2, xz |
format | string | ❌ | default | Custom log format template |
Real-World Scenarios
Logging Exceptions
This example records detailed logs for different failure cases:
import asyncio
from loguru import logger
from simplejrpc.app import ServerApplication
from simplejrpc.response import jsonify
sock_path = "/xxx/app.sock"
config_path = "/xxx/config.yaml"
app = ServerApplication(socket_path=sock_path, config_path=config_path)
@app.route(name="get_config_info")
async def get_config_info():
""" Get configuration information """
data = ""
try:
with open("config.ini", mode="r", encoding="utf-8") as f:
data = f.read()
except Exception as e:
logger.error(f"读取配置失败,错误信息:{e}")
return jsonify(data=data, msg="OK")
if __name__ == "__main__":
asyncio.run(app.run())Best Practices
Choosing a Log Level
# Log level guidance
from loguru import logger
# TRACE: most detailed debug info (usually not used in production)
logger.trace("变量值: x={}, y={}", x, y)
# DEBUG: debugging info that explains program flow
logger.debug("开始处理用户请求: {}", request_id)
# INFO: general information about important business flows
logger.info("用户 {} 登录成功", username)
# SUCCESS: successful operations (loguru-specific)
logger.success("数据备份完成,文件大小: {} MB", file_size)
# WARNING: something to watch that does not break normal operation
logger.warning("API 调用频率过高,用户: {}", user_id)
# ERROR: a failure that affects functionality but does not crash the app
logger.error("数据库连接失败,尝试重连中...")
# CRITICAL: a severe failure that may stop the service
logger.critical("系统内存不足,即将关闭服务")Performance tips
- Enable async writes with
enqueue=Truein production. - Set a sensible level and avoid excessive DEBUG logs.
- Use rotation and compression to control disk usage.
- Avoid verbose logging inside hot functions.
- Prefer structured logs for later analysis.
Security notes
- Never log passwords, API keys or other secrets.
- Mask personal information.
- Set correct access permissions on log files.
- Delete expired log files regularly.
- Turn off
diagnosein production.
Summary
A good logging system is the foundation for monitoring and troubleshooting. Configured well, logs let you:
- Find problems quickly: detailed errors and stack traces
- Monitor performance: timing and frequency of key operations
- Improve security: record security events and suspicious behaviour
- Support analysis: structured logs feed data analysis
- Move faster: clear logs explain what the program is doing
Good logs record not only what happened, but why and in what context.
