markup-tg-logger


Namemarkup-tg-logger JSON
Version 0.1.2 PyPI version JSON
download
home_pageNone
SummaryTelegram logging with full HTML support and optional MarkdownV2
upload_time2024-06-14 04:15:03
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseNone
keywords html markdownv2 telegram logger logging
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 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](https://github.com/korandr/markup-tg-logger/blob/main/README.ru.md)

### 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](#installation)
- [Quick Start](#quick-start)
- [Documentation](#documentation)
- [Useful links](#useful-links)
- [Feedback](#feedback)

## Installation

Python version 3.9 or higher is required.

Installation from the PyPI repository:

```bash
pip install markup-tg-logger
```

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

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

Package import:

```python
import markup_tg_logger
```

## Quick Start

### HTML template

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

```python
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]((https://core.telegram.org/bots/api#html-style)) 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:

```python
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

```python
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](https://github.com/korandr/markup-tg-logger/tree/main/src/examples)

## Documentation

[Here](https://github.com/korandr/markup-tg-logger/wiki) you can find the documentation for the library.

## Useful links

- [Python logging Docs](https://docs.python.org/3/library/logging.html#module-logging)
- [Python logging Docs - Handler](https://docs.python.org/3/library/logging.html#handler-objects)
- [Python logging Docs - Formatter](https://docs.python.org/3/library/logging.html#formatter-objects)
- [Telegram - Create Bot](https://core.telegram.org/bots/features#botfather)
- [Telegram Bot API - HTML](https://docs.python.org/3/library/logging.html#module-logging)
- [Telegram Bot API - sendMessage](https://core.telegram.org/bots/api#sendmessage)
- [Show Json Bot - Get user_id](https://t.me/ShowJsonBot)


## Feedback
Developer: Andrey Korovyanskiy | [andrey.korovyansky@gmail.com](mailto:andrey.korovyansky@gmail.com) 

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "markup-tg-logger",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "HTML, MarkdownV2, Telegram, logger, logging",
    "author": null,
    "author_email": "korandr <andrey.korovyansky@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/c4/c8/81b76d5b70f05395039e9497f59dacac88d60f1c900f6b21eb12811f9052/markup_tg_logger-0.1.2.tar.gz",
    "platform": null,
    "description": "# markup-tg-logger\nAn 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.\n\n[Read this in Russian](https://github.com/korandr/markup-tg-logger/blob/main/README.ru.md)\n\n### Features\n- Plain mode without markup.\n- HTML formatting of the fmt string.\n- Large text is automatically split into multiple messages according to the Telegram limit. Formatting is preserved.\n- Disable escaping of special characters.\n- Pre-configured formatters for markup in a code block of the entire message or only the call stack on error.\n- Flexible modification of pre-configured behavior by creating child classes.\"\n\n## Contents\n- [Installation](#installation)\n- [Quick Start](#quick-start)\n- [Documentation](#documentation)\n- [Useful links](#useful-links)\n- [Feedback](#feedback)\n\n## Installation\n\nPython version 3.9 or higher is required.\n\nInstallation from the PyPI repository:\n\n```bash\npip install markup-tg-logger\n```\n\nInstallation from a GitHub repository (requires pip version 20 and above).\n\n```bash\npip install git+https://github.com/korandr/markup-tg-logger.git\n```\n\nPackage import:\n\n```python\nimport markup_tg_logger\n```\n\n## Quick Start\n\n### HTML template\n\nExample of setting up a Telegram logger with HTML formatting of the fmt template:\n\n```python\nimport logging\nfrom markup_tg_logger import HtmlTelegramFormatter, BaseTelegramHandler\n\n\nBOT_TOKEN = 'bot_token_here'\nCHAT_ID = 'user_id_or_channel_username'\n\nFORMAT = '''<b>{levelname}</b>\n\n<u>{asctime}</u>\n\n<i>{message}</i>\n\n<pre><code class=\"language-bash\">(Line: {lineno} [{pathname}])</code></pre>\n'''\n\nformatter = HtmlTelegramFormatter(\n    fmt = FORMAT,\n    datefmt = '%d-%m-%Y %H:%M:%S',\n    style = '{',\n)\n\nhandler = BaseTelegramHandler(\n    bot_token = BOT_TOKEN,\n    chat_id = CHAT_ID,\n)\n\nhandler.setLevel(logging.DEBUG)\nhandler.setFormatter(formatter)\n\nlogger = logging.getLogger('markup_tg_logger')\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(handler)\n\nlogger.info('Hello HTML world! \\n Any special characters: ><& <3')\n```\n\nWhen using `HtmlTelegramFormatter`, you can specify any HTML tags [supported by the Telegram API]((https://core.telegram.org/bots/api#html-style)) in the `fmt` string.       \nAt 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.\n\nThe `HtmlTelegramFormatter` class allows you to customize the formatting of regular messages only. Traceback output will not be formatted. \n\n### Formatted traceback output\n\nExample of setting up a Telegram logger with HTML formatting of the fmt template and formatted traceback output:\n\n```python\nimport logging\nfrom markup_tg_logger import HtmlTracebackTelegramFormatter, BaseTelegramHandler\n\n\nBOT_TOKEN = 'bot_token_here'\nCHAT_ID = 'user_id_or_channel_username'\n\nformatter = HtmlTracebackTelegramFormatter(\n    fmt = '<b>{levelname}</b>\\n{asctime}\\n\\n{message}',\n    datefmt = '%d-%m-%Y %H:%M:%S',\n    style = '{',\n)\n\nhandler = BaseTelegramHandler(\n    bot_token = BOT_TOKEN,\n    chat_id = CHAT_ID,\n)\n\nhandler.setLevel(logging.ERROR)\nhandler.setFormatter(formatter)\n\nlogger = logging.getLogger('markup_tg_logger')\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(handler)\n\ntry:\n    raise ValueError('Error <description>')\nexcept Exception as e:\n    logger.exception(e)\n```\n\nThe `HtmlTracebackTelegramFormatter` class works similarly to `HtmlTelegramFormatter`, but additionally formats the traceback string into a code block (`<pre><code class=\"language-python\">...`)   \n\nPlease note that in this example, the logging level `ERROR` is also specified.   \n\nYou can also use the `CodeTelegramFormatter` class, which formats the entire logger output into a code block.   \n\n### Notification control\n\nExample of setting up a simple Telegram logger without markup and with notification control\n\n```python\nimport time\nimport logging\nfrom markup_tg_logger import BaseTelegramFormatter, BaseTelegramHandler, LevelNotifier\n\n\nBOT_TOKEN = 'bot_token_here'\nCHAT_ID = 'user_id_or_channel_username'\n\nformatter = BaseTelegramFormatter(\n    fmt = '{levelname}\\n{asctime}\\n\\n{message}',\n    datefmt = '%d-%m-%Y %H:%M:%S',\n    style = '{'\n)\n\nhandler = BaseTelegramHandler(\n    bot_token = BOT_TOKEN,\n    chat_id = CHAT_ID,\n    disable_notification = LevelNotifier(logging.ERROR)\n)\n\nhandler.setLevel(logging.DEBUG)\nhandler.setFormatter(formatter)\n\nlogger = logging.getLogger('markup_tg_logger')\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(handler)\n\nlogger.info('Message without notification')\ntime.sleep(5)\nlogger.critical('Important notification message')\n```\n\nThe `disable_notification` argument can accept either a `bool` value (according to the Telegram Bot API) or an `INotifier` interface object.   \nIn this case, a `LevelNotifier` object with the level `ERROR` is passed, so notifications will only be sent for the `ERROR` level and above.    \n\n\n[See the code from the examples](https://github.com/korandr/markup-tg-logger/tree/main/src/examples)\n\n## Documentation\n\n[Here](https://github.com/korandr/markup-tg-logger/wiki) you can find the documentation for the library.\n\n## Useful links\n\n- [Python logging Docs](https://docs.python.org/3/library/logging.html#module-logging)\n- [Python logging Docs - Handler](https://docs.python.org/3/library/logging.html#handler-objects)\n- [Python logging Docs - Formatter](https://docs.python.org/3/library/logging.html#formatter-objects)\n- [Telegram - Create Bot](https://core.telegram.org/bots/features#botfather)\n- [Telegram Bot API - HTML](https://docs.python.org/3/library/logging.html#module-logging)\n- [Telegram Bot API - sendMessage](https://core.telegram.org/bots/api#sendmessage)\n- [Show Json Bot - Get user_id](https://t.me/ShowJsonBot)\n\n\n## Feedback\nDeveloper: Andrey Korovyanskiy | [andrey.korovyansky@gmail.com](mailto:andrey.korovyansky@gmail.com) \n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Telegram logging with full HTML support and optional MarkdownV2",
    "version": "0.1.2",
    "project_urls": {
        "Documentation": "https://github.com/korandr/markup-tg-logger/wiki",
        "Github": "https://github.com/korandr/markup-tg-logger"
    },
    "split_keywords": [
        "html",
        " markdownv2",
        " telegram",
        " logger",
        " logging"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "549e0f2e1fd0aabffc5080e2960505c836e812c891b045a56a9d8fff55d2bc40",
                "md5": "ad8cafd28c6d568973508b0f8d94b393",
                "sha256": "a55cf1134c673c2958ea3b622d421d53f20954dfcedbc4165aef66bcda018f34"
            },
            "downloads": -1,
            "filename": "markup_tg_logger-0.1.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "ad8cafd28c6d568973508b0f8d94b393",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 13817,
            "upload_time": "2024-06-14T04:15:01",
            "upload_time_iso_8601": "2024-06-14T04:15:01.481178Z",
            "url": "https://files.pythonhosted.org/packages/54/9e/0f2e1fd0aabffc5080e2960505c836e812c891b045a56a9d8fff55d2bc40/markup_tg_logger-0.1.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c4c881b76d5b70f05395039e9497f59dacac88d60f1c900f6b21eb12811f9052",
                "md5": "8d5dff2a9aae5117b03dec1cbb2c4293",
                "sha256": "ff820b0d2e615cca3ba681f45785f1fc9061da6fab7751deca9d44e67e8c82c1"
            },
            "downloads": -1,
            "filename": "markup_tg_logger-0.1.2.tar.gz",
            "has_sig": false,
            "md5_digest": "8d5dff2a9aae5117b03dec1cbb2c4293",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 11369,
            "upload_time": "2024-06-14T04:15:03",
            "upload_time_iso_8601": "2024-06-14T04:15:03.658305Z",
            "url": "https://files.pythonhosted.org/packages/c4/c8/81b76d5b70f05395039e9497f59dacac88d60f1c900f6b21eb12811f9052/markup_tg_logger-0.1.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-06-14 04:15:03",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "korandr",
    "github_project": "markup-tg-logger",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "markup-tg-logger"
}
        
Elapsed time: 1.01212s