A Python logging handler that sends logs to Telegram
Project description
Python Telegram Logging
A Python logging handler that sends logs to Telegram with support for both synchronous and asynchronous operations.
Table of Contents
- Who is Target User?
- Features
- Installation
- Quick Start
- Advanced Usage
- Handler Comparison
- Technical Details
- Requirements
- License
- TODO
Who is Target User?
This package is ideal for developers with simple Python applications who want to receive error notifications directly via Telegram. Suppose you lack the resources to maintain a full-fledged logging/alerting setup using tools like Kibana, Elasticsearch, or Grafana, or do not have time to configure complex alert rules. In that case, this package provides a lightweight and hassle-free solution
Features
-
🚀 Multiple Handler Types:
SyncTelegramHandler: Synchronous handler usingrequestsAsyncTelegramHandler: Asynchronous handler with built-in queue usingaiohttpQueuedTelegramHandler: Thread-safe queued wrapper for synchronous handlers only (currently)
-
🔒 Thread Safety: All handlers are thread-safe and can be used in multi-threaded applications
-
🎨 Formatting Support:
- HTML formatting
- Markdown formatting
- Custom formatters support
-
🛡️ Error Handling:
- Rate limiting with configurable strategies (TODO)
- Automatic message splitting for long logs
- Custom error callbacks (in case if message is not sent, raised exception)
Installation
pip install python-telegram-logging
Quick Start
Use one of the exanple below or check examples folder.
Synchronous Usage
import logging
from python_telegram_logging import SyncTelegramHandler, ParseMode
# Create and configure the handler
handler = SyncTelegramHandler(
token="YOUR_BOT_TOKEN",
chat_id="YOUR_CHAT_ID",
parse_mode=ParseMode.HTML
)
# Add it to your logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(handler)
# Use it!
logger.info("Hello from Python! 🐍")
Asynchronous Usage
import logging
from python_telegram_logging import AsyncTelegramHandler, ParseMode
# Create and configure the handler
handler = AsyncTelegramHandler(
token="YOUR_BOT_TOKEN",
chat_id="YOUR_CHAT_ID",
parse_mode=ParseMode.HTML
)
# Add it to your logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(handler)
# Use it in your async code!
logger.info("Hello from async Python! 🐍")
Queued Usage (for synchronous handlers)
⚠️ Important:
QueuedTelegramHandleris designed to work with synchronous handlers only. For asynchronous applications, useAsyncTelegramHandlerdirectly as it already includes queue functionality.
import logging
from python_telegram_logging import SyncTelegramHandler, QueuedTelegramHandler, ParseMode
# Create the base synchronous handler
base_handler = SyncTelegramHandler(
token="YOUR_BOT_TOKEN",
chat_id="YOUR_CHAT_ID",
parse_mode=ParseMode.HTML
)
# Wrap it in a queued handler for non-blocking operation
handler = QueuedTelegramHandler(base_handler, queue_size=1000)
# Add it to your logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(handler)
# Use it!
logger.info("Hello from queued logger! 🐍")
Advanced Usage
Custom Formatting
import logging
from python_telegram_logging import SyncTelegramHandler, ParseMode
# Create a custom formatter
class HTMLFormatter(logging.Formatter):
def format(self, record):
return f"""
<b>{record.levelname}</b>: {record.getMessage()}
<code>
File: {record.filename}
Line: {record.lineno}
</code>
"""
# Use the custom formatter
handler = SyncTelegramHandler(
token="YOUR_BOT_TOKEN",
chat_id="YOUR_CHAT_ID",
parse_mode=ParseMode.HTML
)
handler.setFormatter(HTMLFormatter())
Error Handling
from python_telegram_logging import SyncTelegramHandler
def on_error(error: Exception):
print(f"Failed to send log to Telegram: {error}")
handler = SyncTelegramHandler(
token="YOUR_BOT_TOKEN",
chat_id="YOUR_CHAT_ID",
error_callback=on_error
)
Handler Comparison
| Feature | SyncTelegramHandler | AsyncTelegramHandler | QueuedTelegramHandler |
|---|---|---|---|
| Blocking | Yes | No | No |
| Thread-Safe | Yes | Yes | Yes |
| Dependencies | requests | aiohttp | - |
| Use Case | Simple scripts | Async applications | High-performance sync apps |
| Message Order | Guaranteed | Best-effort | Best-effort |
| Queue Support | No | Built-in | Yes (sync handlers only) |
| Handler Type | Sync | Async | Sync wrapper |
Technical Details
- Rate limiting: Implements a token bucket algorithm to respect Telegram's rate limits
- Message splitting: Automatically splits messages longer than 4096 characters
- Thread safety: Uses appropriate synchronization primitives for each context
- Resource management: Proper cleanup of resources on handler close
- Error handling: Configurable error callbacks and retry strategies
Requirements
- Python 3.8+
requests>= 2.31.0aiohttp>= 3.8.6
License
MIT License
Contributing
Feel free to open issues or PR.
Please install and run pre-commit rules .pre-commit-config.yaml:
pre-commit install && ` pre-commit run --all-files
TODO
- what if queue is full?
Notes: Configurable blocking behavior: Added block_on_full option to either block when the queue is full or continue with alternative handling. Selective message dropping: Added discard_level_on_full to allow dropping less important messages (e.g., DEBUG) while ensuring critical messages (ERROR, CRITICAL) are handled. Timeout control: Added timeout parameter to prevent indefinite blocking if block_on_full is True. Default behavior: By default, it will:
- Not block (block_on_full=False)
- Silently drop DEBUG messages when full
- Call handleError() for more important messages
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 python_telegram_logging-0.0.2.tar.gz.
File metadata
- Download URL: python_telegram_logging-0.0.2.tar.gz
- Upload date:
- Size: 17.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.0.1 CPython/3.12.8
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4e1d91c3186e1dea34fdb83e7810f3b4dfb233a72ab1c8225e6f91ba124bc032
|
|
| MD5 |
7a83c67f706b6c8aa4e6be2cb13d9123
|
|
| BLAKE2b-256 |
dce9a7440346e4039a2404b9954a62cf87970cbc8b7e666e6a58411977f89d06
|
File details
Details for the file python_telegram_logging-0.0.2-py3-none-any.whl.
File metadata
- Download URL: python_telegram_logging-0.0.2-py3-none-any.whl
- Upload date:
- Size: 16.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.0.1 CPython/3.12.8
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e5dac1c3ce48016037c53447be0091342ef5835a3049b800934a7782e925beda
|
|
| MD5 |
5fd59ec262e6edbb8009935d7e0489fc
|
|
| BLAKE2b-256 |
625c616f8263b3fad590dc90b50ab814ceae896f24249a482ad11b40bc9aa03a
|