Skip to main content

Telegram logging with full HTML support and optional MarkdownV2

Project description

markup-tg-logger

An extension to Python's standard logging module for logging to a Telegram chat or channel with built-in HTML support and the ability to add MarkdownV2.

Read this in Russian

Features

  • Plain mode without markup.
  • HTML formatting of the fmt string.
  • Large text is automatically split into multiple messages according to the Telegram limit. Formatting is preserved.
  • Disable escaping of special characters.
  • Pre-configured formatters for markup in a code block of the entire message or only the call stack on error.
  • Flexible modification of pre-configured behavior by creating child classes."

Contents

Installation

Python version 3.9 or higher is required.

Installation from the PyPI repository:

pip install markup-tg-logger

Installation from a GitHub repository (requires pip version 20 and above).

pip install git+https://github.com/korandr/markup-tg-logger.git

Package import:

import markup_tg_logger

Quick Start

HTML template

Example of setting up a Telegram logger with HTML formatting of the fmt template:

import logging
from markup_tg_logger import HtmlTelegramFormatter, BaseTelegramHandler


BOT_TOKEN = 'bot_token_here'
CHAT_ID = 'user_id_or_channel_username'

FORMAT = '''<b>{levelname}</b>

<u>{asctime}</u>

<i>{message}</i>

<pre><code class="language-bash">(Line: {lineno} [{pathname}])</code></pre>
'''

formatter = HtmlTelegramFormatter(
    fmt = FORMAT,
    datefmt = '%d-%m-%Y %H:%M:%S',
    style = '{',
)

handler = BaseTelegramHandler(
    bot_token = BOT_TOKEN,
    chat_id = CHAT_ID,
)

handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)

logger = logging.getLogger('markup_tg_logger')
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)

logger.info('Hello HTML world! \n Any special characters: ><& <3')

When using HtmlTelegramFormatter, you can specify any HTML tags supported by the Telegram API in the fmt string.
At the same time, all characters <, > and & in the message string will be escaped and will not affect the markup. If you whant to change this behavior, you need to specify the is_escape_markup=False parameter in the constructor of the HtmlTelegramFormatter class.

The HtmlTelegramFormatter class allows you to customize the formatting of regular messages only. Traceback output will not be formatted.

Formatted traceback output

Example of setting up a Telegram logger with HTML formatting of the fmt template and formatted traceback output:

import logging
from markup_tg_logger import HtmlTracebackTelegramFormatter, BaseTelegramHandler


BOT_TOKEN = 'bot_token_here'
CHAT_ID = 'user_id_or_channel_username'

formatter = HtmlTracebackTelegramFormatter(
    fmt = '<b>{levelname}</b>\n{asctime}\n\n{message}',
    datefmt = '%d-%m-%Y %H:%M:%S',
    style = '{',
)

handler = BaseTelegramHandler(
    bot_token = BOT_TOKEN,
    chat_id = CHAT_ID,
)

handler.setLevel(logging.ERROR)
handler.setFormatter(formatter)

logger = logging.getLogger('markup_tg_logger')
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)

try:
    raise ValueError('Error <description>')
except Exception as e:
    logger.exception(e)

The HtmlTracebackTelegramFormatter class works similarly to HtmlTelegramFormatter, but additionally formats the traceback string into a code block (<pre><code class="language-python">...)

Please note that in this example, the logging level ERROR is also specified.

You can also use the CodeTelegramFormatter class, which formats the entire logger output into a code block.

Notification control

Example of setting up a simple Telegram logger without markup and with notification control

import time
import logging
from markup_tg_logger import BaseTelegramFormatter, BaseTelegramHandler, LevelNotifier


BOT_TOKEN = 'bot_token_here'
CHAT_ID = 'user_id_or_channel_username'

formatter = BaseTelegramFormatter(
    fmt = '{levelname}\n{asctime}\n\n{message}',
    datefmt = '%d-%m-%Y %H:%M:%S',
    style = '{'
)

handler = BaseTelegramHandler(
    bot_token = BOT_TOKEN,
    chat_id = CHAT_ID,
    disable_notification = LevelNotifier(logging.ERROR)
)

handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)

logger = logging.getLogger('markup_tg_logger')
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)

logger.info('Message without notification')
time.sleep(5)
logger.critical('Important notification message')

The disable_notification argument can accept either a bool value (according to the Telegram Bot API) or an INotifier interface object.
In this case, a LevelNotifier object with the level ERROR is passed, so notifications will only be sent for the ERROR level and above.

See the code from the examples

Documentation

Here you can find the documentation for the library.

Useful links

Feedback

Developer: Andrey Korovyanskiy | andrey.korovyansky@gmail.com

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

markup_tg_logger-0.1.3.tar.gz (11.4 kB view details)

Uploaded Source

Built Distribution

markup_tg_logger-0.1.3-py3-none-any.whl (14.0 kB view details)

Uploaded Python 3

File details

Details for the file markup_tg_logger-0.1.3.tar.gz.

File metadata

  • Download URL: markup_tg_logger-0.1.3.tar.gz
  • Upload date:
  • Size: 11.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.10.12

File hashes

Hashes for markup_tg_logger-0.1.3.tar.gz
Algorithm Hash digest
SHA256 116cbcf36c5b1c86bf914b76dc8ab0471c8ddabf67be9e40d7d1ab4b1503b98b
MD5 5342c02d1b04a3463238ed781b4bd38b
BLAKE2b-256 7ea22e9c9894d4c20bc82cd2ccb3c8c544e830b1dd9ca2e58b0dbc8d83e3db86

See more details on using hashes here.

File details

Details for the file markup_tg_logger-0.1.3-py3-none-any.whl.

File metadata

File hashes

Hashes for markup_tg_logger-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 7aaf69f7171808cb974d002960780b3ed3633f67548b54b0c5d736a8fae5ed27
MD5 2364499a4acb8e6e5f91e04395b42909
BLAKE2b-256 d9b2d1fa83a04d6b670bee1dac78ddffebac15401cb80ac1b5c1fce6ea49d4a9

See more details on using hashes here.

Supported by

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