# TGBot-Logging
[![PyPI version](https://badge.fury.io/py/tgbot-logging.svg)](https://badge.fury.io/py/tgbot-logging)
[![Python Support](https://img.shields.io/pypi/pyversions/tgbot-logging.svg)](https://pypi.org/project/tgbot-logging/)
[![Documentation Status](https://readthedocs.org/projects/tgbot-logging/badge/?version=latest)](https://tgbot-logging.readthedocs.io/en/latest/?badge=latest)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Code Coverage](https://img.shields.io/badge/coverage-92%25-brightgreen.svg)](https://github.com/bykovk-pro/tgbot-logging)
[![Code Style: Black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
A Python logging handler that sends log messages to Telegram chats with advanced features like message batching, retries, and formatting.
## Features
- Send log messages to one or multiple Telegram chats
- Support for HTML and MarkdownV2 formatting
- Message batching for better performance
- Automatic retries for failed messages
- Rate limiting and error handling
- Customizable log format and emojis
- Support for project names and hashtags
- Environment variables support
- Async/await support with context manager
- Graceful shutdown with signal handling
- Cross-platform compatibility
- Type hints and documentation
- 96% test coverage
## Quick Start
1. Install the package:
```bash
pip install tgbot-logging
```
2. Basic usage:
```python
import logging
from tgbot_logging import TelegramHandler
# Create logger
logger = logging.getLogger('MyApp')
logger.setLevel(logging.DEBUG)
# Create TelegramHandler
telegram_handler = TelegramHandler(
token='YOUR_BOT_TOKEN',
chat_ids=['YOUR_CHAT_ID'],
level=logging.INFO,
project_name='MyApp', # Optional project name
project_emoji='🚀', # Optional project emoji
parse_mode='HTML' # Support for HTML formatting
)
# Add handler to logger
logger.addHandler(telegram_handler)
# Example usage
logger.info('This is an info message')
logger.error('This is an error message')
```
3. Advanced usage with batching and retries:
```python
telegram_handler = TelegramHandler(
token='YOUR_BOT_TOKEN',
chat_ids=['YOUR_CHAT_ID'],
level=logging.INFO,
batch_size=5, # Batch 5 messages together
batch_interval=2.0, # Send batch every 2 seconds or when full
max_retries=3, # Retry failed messages 3 times
retry_delay=1.0, # Wait 1 second between retries
parse_mode='HTML', # Support for HTML formatting
fmt='<b>%(levelname)s</b> [%(asctime)s]\n%(message)s' # Custom HTML format
)
```
4. Using async context manager:
```python
async with TelegramHandler(
token='YOUR_BOT_TOKEN',
chat_ids=['YOUR_CHAT_ID'],
level=logging.INFO
) as handler:
logger = logging.getLogger('MyApp')
logger.addHandler(handler)
logger.info('This message will be sent before context exit')
# Handler will be properly closed after context exit
```
5. Environment variables support:
```bash
# .env file
TELEGRAM_BOT_TOKEN=your_bot_token
TELEGRAM_CHAT_IDS=123456789,987654321
LOG_LEVEL=INFO
BATCH_SIZE=5
BATCH_INTERVAL=2.0
MAX_RETRIES=3
RETRY_DELAY=1.0
PARSE_MODE=HTML
PROJECT_NAME=MyProject
PROJECT_EMOJI=🚀
```
## Documentation
Full documentation is available at [tgbot-logging.readthedocs.io](https://tgbot-logging.readthedocs.io/), including:
- Detailed installation instructions
- Configuration options
- Advanced usage examples
- API reference
- Development guide
## Features in Detail
### Message Formatting
- Support for HTML and MarkdownV2 formatting
- Custom message formats with templates
- Custom date/time formats
- Project names and emojis
- Automatic hashtags
- Level-specific emojis
### Message Batching
- Configurable batch size
- Configurable batch interval
- Automatic batch flushing
- Memory-efficient queue system
- Per-chat batching
### Error Handling
- Automatic retries for failed messages
- Rate limit handling
- Network error handling
- Timeout handling
- Graceful error recovery
- Per-chat error isolation
### Performance
- Asynchronous message sending
- Message batching
- Rate limiting
- Memory optimization
- Cross-platform compatibility
### Shutdown Handling
- Graceful shutdown support
- Signal handling (SIGTERM, SIGINT, SIGHUP)
- Message queue flushing before exit
- Resource cleanup
- Async context manager support
### Development Features
- Type hints for better IDE support
- Comprehensive test suite (96% coverage)
- Detailed documentation
- Code style compliance (Black)
- Security checks (Bandit)
## Development Installation
For development with testing tools and code formatting:
```bash
pip install -e ".[dev]"
# or
pip install -r requirements-dev.txt
```
## Testing
The project includes several types of tests to ensure reliability and functionality:
### Unit Tests
Located in `tests/test_handler.py` and `tests/test_bot.py`:
- `test_handler.py`: Tests for the TelegramHandler class functionality
- Message sending and formatting
- Batching and rate limiting
- Error handling and retries
- Signal handling and graceful shutdown
- Async context manager support
- `test_bot.py`: Tests for the underlying Telegram bot functionality
- Bot initialization and configuration
- Message sending and error handling
- Rate limit handling
- Network error recovery
### Example Usage and Integration Tests
Located in `tests/examples.py`:
- Complete examples of handler usage
- Performance testing
- Error recovery testing
- Multi-project logging examples
- Real-world usage scenarios
To run the tests:
```bash
# Run all tests with coverage report
pytest -v --cov=tgbot_logging --cov-report=term-missing:skip-covered
# Run specific test file
pytest tests/test_handler.py -v
# Run specific test
pytest tests/test_handler.py::test_emit_single_message -v
```
For manual testing and examples, run:
```bash
# Set up environment variables in .env file first
python tests/examples.py
```
## Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Run tests and linting
5. Submit a pull request
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## Support
- [Documentation](https://tgbot-logging.readthedocs.io/)
- [GitHub Issues](https://github.com/bykovk-pro/tgbot-logging/issues)
- [PyPI Project](https://pypi.org/project/tgbot-logging/)
Raw data
{
"_id": null,
"home_page": "https://github.com/bykovk-pro/tgbot-logging",
"name": "tgbot-logging",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": "telegram, logging, handler, async, batching, monitoring, notifications, chat, bot, signal, shutdown, graceful",
"author": "Kirill Bykov",
"author_email": "me@bykovk.pro",
"download_url": "https://files.pythonhosted.org/packages/fa/ea/a0d9b08ff7d057af5b537a6711fd4f0ff3cdadade74235e170836e2247a1/tgbot_logging-1.0.2.tar.gz",
"platform": null,
"description": "# TGBot-Logging\n\n[![PyPI version](https://badge.fury.io/py/tgbot-logging.svg)](https://badge.fury.io/py/tgbot-logging)\n[![Python Support](https://img.shields.io/pypi/pyversions/tgbot-logging.svg)](https://pypi.org/project/tgbot-logging/)\n[![Documentation Status](https://readthedocs.org/projects/tgbot-logging/badge/?version=latest)](https://tgbot-logging.readthedocs.io/en/latest/?badge=latest)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Code Coverage](https://img.shields.io/badge/coverage-92%25-brightgreen.svg)](https://github.com/bykovk-pro/tgbot-logging)\n[![Code Style: Black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n\nA Python logging handler that sends log messages to Telegram chats with advanced features like message batching, retries, and formatting.\n\n## Features\n\n- Send log messages to one or multiple Telegram chats\n- Support for HTML and MarkdownV2 formatting\n- Message batching for better performance\n- Automatic retries for failed messages\n- Rate limiting and error handling\n- Customizable log format and emojis\n- Support for project names and hashtags\n- Environment variables support\n- Async/await support with context manager\n- Graceful shutdown with signal handling\n- Cross-platform compatibility\n- Type hints and documentation\n- 96% test coverage\n\n## Quick Start\n\n1. Install the package:\n```bash\npip install tgbot-logging\n```\n\n2. Basic usage:\n```python\nimport logging\nfrom tgbot_logging import TelegramHandler\n\n# Create logger\nlogger = logging.getLogger('MyApp')\nlogger.setLevel(logging.DEBUG)\n\n# Create TelegramHandler\ntelegram_handler = TelegramHandler(\n token='YOUR_BOT_TOKEN',\n chat_ids=['YOUR_CHAT_ID'],\n level=logging.INFO,\n project_name='MyApp', # Optional project name\n project_emoji='\ud83d\ude80', # Optional project emoji\n parse_mode='HTML' # Support for HTML formatting\n)\n\n# Add handler to logger\nlogger.addHandler(telegram_handler)\n\n# Example usage\nlogger.info('This is an info message')\nlogger.error('This is an error message')\n```\n\n3. Advanced usage with batching and retries:\n```python\ntelegram_handler = TelegramHandler(\n token='YOUR_BOT_TOKEN',\n chat_ids=['YOUR_CHAT_ID'],\n level=logging.INFO,\n batch_size=5, # Batch 5 messages together\n batch_interval=2.0, # Send batch every 2 seconds or when full\n max_retries=3, # Retry failed messages 3 times\n retry_delay=1.0, # Wait 1 second between retries\n parse_mode='HTML', # Support for HTML formatting\n fmt='<b>%(levelname)s</b> [%(asctime)s]\\n%(message)s' # Custom HTML format\n)\n```\n\n4. Using async context manager:\n```python\nasync with TelegramHandler(\n token='YOUR_BOT_TOKEN',\n chat_ids=['YOUR_CHAT_ID'],\n level=logging.INFO\n) as handler:\n logger = logging.getLogger('MyApp')\n logger.addHandler(handler)\n logger.info('This message will be sent before context exit')\n# Handler will be properly closed after context exit\n```\n\n5. Environment variables support:\n```bash\n# .env file\nTELEGRAM_BOT_TOKEN=your_bot_token\nTELEGRAM_CHAT_IDS=123456789,987654321\nLOG_LEVEL=INFO\nBATCH_SIZE=5\nBATCH_INTERVAL=2.0\nMAX_RETRIES=3\nRETRY_DELAY=1.0\nPARSE_MODE=HTML\nPROJECT_NAME=MyProject\nPROJECT_EMOJI=\ud83d\ude80\n```\n\n## Documentation\n\nFull documentation is available at [tgbot-logging.readthedocs.io](https://tgbot-logging.readthedocs.io/), including:\n\n- Detailed installation instructions\n- Configuration options\n- Advanced usage examples\n- API reference\n- Development guide\n\n## Features in Detail\n\n### Message Formatting\n\n- Support for HTML and MarkdownV2 formatting\n- Custom message formats with templates\n- Custom date/time formats\n- Project names and emojis\n- Automatic hashtags\n- Level-specific emojis\n\n### Message Batching\n\n- Configurable batch size\n- Configurable batch interval\n- Automatic batch flushing\n- Memory-efficient queue system\n- Per-chat batching\n\n### Error Handling\n\n- Automatic retries for failed messages\n- Rate limit handling\n- Network error handling\n- Timeout handling\n- Graceful error recovery\n- Per-chat error isolation\n\n### Performance\n\n- Asynchronous message sending\n- Message batching\n- Rate limiting\n- Memory optimization\n- Cross-platform compatibility\n\n### Shutdown Handling\n\n- Graceful shutdown support\n- Signal handling (SIGTERM, SIGINT, SIGHUP)\n- Message queue flushing before exit\n- Resource cleanup\n- Async context manager support\n\n### Development Features\n\n- Type hints for better IDE support\n- Comprehensive test suite (96% coverage)\n- Detailed documentation\n- Code style compliance (Black)\n- Security checks (Bandit)\n\n## Development Installation\n\nFor development with testing tools and code formatting:\n\n```bash\npip install -e \".[dev]\"\n# or\npip install -r requirements-dev.txt\n```\n\n## Testing\n\nThe project includes several types of tests to ensure reliability and functionality:\n\n### Unit Tests\n\nLocated in `tests/test_handler.py` and `tests/test_bot.py`:\n- `test_handler.py`: Tests for the TelegramHandler class functionality\n - Message sending and formatting\n - Batching and rate limiting\n - Error handling and retries\n - Signal handling and graceful shutdown\n - Async context manager support\n\n- `test_bot.py`: Tests for the underlying Telegram bot functionality\n - Bot initialization and configuration\n - Message sending and error handling\n - Rate limit handling\n - Network error recovery\n\n### Example Usage and Integration Tests\n\nLocated in `tests/examples.py`:\n- Complete examples of handler usage\n- Performance testing\n- Error recovery testing\n- Multi-project logging examples\n- Real-world usage scenarios\n\nTo run the tests:\n\n```bash\n# Run all tests with coverage report\npytest -v --cov=tgbot_logging --cov-report=term-missing:skip-covered\n\n# Run specific test file\npytest tests/test_handler.py -v\n\n# Run specific test\npytest tests/test_handler.py::test_emit_single_message -v\n```\n\nFor manual testing and examples, run:\n```bash\n# Set up environment variables in .env file first\npython tests/examples.py\n```\n\n## Contributing\n\n1. Fork the repository\n2. Create a feature branch\n3. Make your changes\n4. Run tests and linting\n5. Submit a pull request\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Support\n\n- [Documentation](https://tgbot-logging.readthedocs.io/)\n- [GitHub Issues](https://github.com/bykovk-pro/tgbot-logging/issues)\n- [PyPI Project](https://pypi.org/project/tgbot-logging/)\n",
"bugtrack_url": null,
"license": null,
"summary": "A Python logging handler that sends log messages to Telegram chats",
"version": "1.0.2",
"project_urls": {
"Bug Reports": "https://github.com/bykovk-pro/tgbot-logging/issues",
"Documentation": "https://tgbot-logging.readthedocs.io/",
"Homepage": "https://github.com/bykovk-pro/tgbot-logging",
"Source Code": "https://github.com/bykovk-pro/tgbot-logging"
},
"split_keywords": [
"telegram",
" logging",
" handler",
" async",
" batching",
" monitoring",
" notifications",
" chat",
" bot",
" signal",
" shutdown",
" graceful"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "cb442edc82b87c0d94dac242d08928ad0eb3129e39e426369b2ea559e135a69d",
"md5": "9f473a2aa639d11ae925ae243d74439e",
"sha256": "e376b2d582a740c0e79f4d3d288b5ab06de0e2e61f73738fa9f49391c4b00ec4"
},
"downloads": -1,
"filename": "tgbot_logging-1.0.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "9f473a2aa639d11ae925ae243d74439e",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 8860,
"upload_time": "2024-12-08T16:17:15",
"upload_time_iso_8601": "2024-12-08T16:17:15.794230Z",
"url": "https://files.pythonhosted.org/packages/cb/44/2edc82b87c0d94dac242d08928ad0eb3129e39e426369b2ea559e135a69d/tgbot_logging-1.0.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "faeaa0d9b08ff7d057af5b537a6711fd4f0ff3cdadade74235e170836e2247a1",
"md5": "af3aa7601621228379650299dcd2297a",
"sha256": "3aeda62c13375834b4091f95560a447e22b10c8e79b39d3c689ae007072e924a"
},
"downloads": -1,
"filename": "tgbot_logging-1.0.2.tar.gz",
"has_sig": false,
"md5_digest": "af3aa7601621228379650299dcd2297a",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 17985,
"upload_time": "2024-12-08T16:17:18",
"upload_time_iso_8601": "2024-12-08T16:17:18.152590Z",
"url": "https://files.pythonhosted.org/packages/fa/ea/a0d9b08ff7d057af5b537a6711fd4f0ff3cdadade74235e170836e2247a1/tgbot_logging-1.0.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-12-08 16:17:18",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "bykovk-pro",
"github_project": "tgbot-logging",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"requirements": [
{
"name": "python-telegram-bot",
"specs": [
[
"==",
"21.0.1"
]
]
},
{
"name": "httpx",
"specs": [
[
">=",
"0.25.2"
]
]
}
],
"lcname": "tgbot-logging"
}