Skip to main content

A Python logging handler that sends log messages to Telegram chats

Project description

TGBot-Logging

PyPI version Python Support Documentation Status License: MIT Code Coverage Code Style: 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:
pip install tgbot-logging
  1. Basic usage:
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')
  1. Advanced usage with batching and retries:
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
)
  1. Using async context manager:
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
  1. Environment variables support:
# .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, 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:

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:

# 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:

# 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 file for details.

Support

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tgbot_logging-1.0.2.tar.gz (18.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tgbot_logging-1.0.2-py3-none-any.whl (8.9 kB view details)

Uploaded Python 3

File details

Details for the file tgbot_logging-1.0.2.tar.gz.

File metadata

  • Download URL: tgbot_logging-1.0.2.tar.gz
  • Upload date:
  • Size: 18.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.13.0

File hashes

Hashes for tgbot_logging-1.0.2.tar.gz
Algorithm Hash digest
SHA256 3aeda62c13375834b4091f95560a447e22b10c8e79b39d3c689ae007072e924a
MD5 af3aa7601621228379650299dcd2297a
BLAKE2b-256 faeaa0d9b08ff7d057af5b537a6711fd4f0ff3cdadade74235e170836e2247a1

See more details on using hashes here.

File details

Details for the file tgbot_logging-1.0.2-py3-none-any.whl.

File metadata

  • Download URL: tgbot_logging-1.0.2-py3-none-any.whl
  • Upload date:
  • Size: 8.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.13.0

File hashes

Hashes for tgbot_logging-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 e376b2d582a740c0e79f4d3d288b5ab06de0e2e61f73738fa9f49391c4b00ec4
MD5 9f473a2aa639d11ae925ae243d74439e
BLAKE2b-256 cb442edc82b87c0d94dac242d08928ad0eb3129e39e426369b2ea559e135a69d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page