A Django logging handler that sends exception logs to a Telegram bot or channel. Exception tracebacks are gracefully formatted into HTML documents and sent directly to the chat to avoid length limits, while standard logs are sent as plain text.
- Smart Formatting: Converts exceptions to Django debug HTML and sends them as an attached file.
- Auto-Discovery: Automatically detects your bot's initialized
chat_id. - Easy Configuration: Simplifies error tracking directly from Django's logging configuration.
- Management Tools: Built-in commands to discover
chat_id, test configurations, and clear chat history.
As this package is hosted on an internal or specific Git repository, you can install it via SSH:
pip install git+ssh://git@github.com/forwalk-org/django_telegram_log.gitBefore using the package, you must have a Telegram bot and a target chat (a private conversation or a group).
- Open Telegram and search for the
@BotFather. - Send
/newbotand follow the instructions to create a new bot. - Copy the HTTP API bot_token.
- Message the bot from your Telegram account (or add it to your group chat and send a message). This enables the library to auto-discover the
chat_id.
In your Django project's settings.py, configure your LOGGING dictionary to use the TelegramHandler:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'telegram': {
'level': 'ERROR',
'class': 'django_telegram_log.handlers.TelegramHandler',
'bot_token': 'YOUR_BOT_TOKEN_HERE',
# 'chat_id': 'YOUR_CHAT_ID_HERE', # Optional! If omitted, the handler will try to fetch it automatically via the getUpdates API.
},
},
'loggers': {
'django': {
'handlers': ['telegram'],
'level': 'ERROR',
'propagate': True,
},
},
}The package provides Django management commands for easier integration and debugging. Be sure to add django_telegram_log to your INSTALLED_APPS:
INSTALLED_APPS = [
# ...
'django_telegram_log',
]If you don't know your chat ID, send a message to the bot on Telegram, then run:
python manage.py telegram_get_chat_id YOUR_BOT_TOKENSimulate a standard error and an exception to verify your settings. If the parameters are already in settings.py, they will be automatically picked up.
python manage.py telegram_test_log --bot_token=XXX --chat_id=YYY
# Or just:
python manage.py telegram_test_logTo clean up old errors generated by tests or spam:
python manage.py telegram_clear_chat YOUR_BOT_TOKEN YOUR_CHAT_ID --amount 50To run the included unit tests locally, clone the repository and run:
cd django_telegram_log
pip install -e .[test]
python -m unittest discover tests -vThis project is licensed under the MIT License. See the LICENSE file for details.
Contributions are welcome! Please feel free to submit a pull request or open an issue on GitHub.
For any questions or inquiries, please contact Maurizio Melani.