├── tests ├── __init__.py ├── test_utils.py ├── test_formatters.py └── test_handlers.py ├── MANIFEST.in ├── .gitignore ├── requirements-dev.txt ├── telegram_handler ├── __main__.py ├── utils.py ├── __init__.py ├── formatters.py └── handlers.py ├── .travis.yml ├── tox.ini ├── LICENSE ├── setup.py ├── HISTORY.rst └── README.rst /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.rst -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .tox/ 2 | .cache/ 3 | .idea/ 4 | .coverage 5 | htmlcov/ -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | requests 2 | mock 3 | pytest 4 | pytest-cov 5 | tox -------------------------------------------------------------------------------- /telegram_handler/__main__.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': # pragma: no cover 2 | from telegram_handler import main 3 | 4 | main() 5 | -------------------------------------------------------------------------------- /telegram_handler/utils.py: -------------------------------------------------------------------------------- 1 | def escape_html(text): 2 | """ 3 | Escapes all html characters in text 4 | 5 | :param str text: 6 | :rtype: str 7 | """ 8 | return text.replace('&', '&').replace('<', '<').replace('>', '>') 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | cache: pip 3 | 4 | python: 5 | - "2.7" 6 | - "3.4" 7 | - "3.5" 8 | - "3.6" 9 | 10 | install: 11 | - pip install tox-travis codecov 12 | 13 | script: 14 | - tox 15 | 16 | after_success: 17 | - codecov 18 | -------------------------------------------------------------------------------- /tests/test_utils.py: -------------------------------------------------------------------------------- 1 | from telegram_handler import utils 2 | 3 | 4 | def test_escape_html(): 5 | html = 'Hello, world! Foo&bar' 6 | 7 | escaped = utils.escape_html(html) 8 | 9 | assert '<' not in escaped 10 | assert '>' not in escaped 11 | assert 'Foo&bar' not in escaped -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27,py30,py34,py35,py36,coverage 3 | 4 | [testenv] 5 | skip_install = True 6 | usedevelop = True 7 | deps= 8 | -rrequirements-dev.txt 9 | commands=py.test tests --cov-fail-under 90 --color=auto --cov=telegram_handler --cov-report=term-missing 10 | 11 | [testenv:coverage] 12 | basepython = python3.5 13 | passenv = CI TRAVIS_BUILD_ID TRAVIS TRAVIS_BRANCH TRAVIS_JOB_NUMBER TRAVIS_PULL_REQUEST TRAVIS_JOB_ID TRAVIS_REPO_SLUG TRAVIS_COMMIT 14 | deps = 15 | codecov>=1.4.0 16 | commands = codecov -e TOXENV -------------------------------------------------------------------------------- /telegram_handler/__init__.py: -------------------------------------------------------------------------------- 1 | from telegram_handler.formatters import * 2 | from telegram_handler.handlers import * 3 | 4 | 5 | def main(): # pragma: no cover 6 | import argparse 7 | 8 | parser = argparse.ArgumentParser('Telegram Logging Handler', description='Helps to retrieve chat_id') 9 | parser.add_argument('token') 10 | 11 | args = parser.parse_args() 12 | token = args.token 13 | 14 | handler = TelegramHandler(token, 'foo') 15 | chat_id = handler.get_chat_id() 16 | if not chat_id: 17 | print('Did not get chat id') 18 | print(handler.last_response.status_code, handler.last_response.text) 19 | exit(-1) 20 | print(chat_id) 21 | 22 | 23 | if __name__ == '__main__': # pragma: no cover 24 | main() 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Alexander Gorokhov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | 3 | with open('README.rst') as readme: 4 | with open('HISTORY.rst') as history: 5 | long_description = readme.read() + '\n\n' + history.read() 6 | 7 | VERSION = '2.2.1' 8 | 9 | setup( 10 | install_requires=['requests'], 11 | name='python-telegram-handler', 12 | version=VERSION, 13 | packages=['telegram_handler'], 14 | url='https://github.com/sashgorokhov/python-telegram-handler', 15 | download_url='https://github.com/sashgorokhov/python-telegram-handler/archive/v%s.zip' % VERSION, 16 | keywords=['telegram', 'logging', 'handler', 'bot'], 17 | classifiers=[ 18 | 'Development Status :: 5 - Production/Stable', 19 | 'Intended Audience :: Developers', 20 | 'License :: OSI Approved :: MIT License', 21 | 'Programming Language :: Python :: 2.7', 22 | 'Programming Language :: Python :: 3', 23 | 'Programming Language :: Python :: 3.4', 24 | 'Programming Language :: Python :: 3.5', 25 | 'Programming Language :: Python :: 3.6', 26 | 'Topic :: Software Development :: Debuggers', 27 | 'Topic :: System :: Logging' 28 | ], 29 | long_description=long_description, 30 | license='MIT License', 31 | author='sashgorokhov', 32 | author_email='sashgorokhov@gmail.com', 33 | description='A python logging handler that sends logs via Telegram Bot Api.', 34 | ) 35 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | History 4 | ------- 5 | 6 | 2.2.0 (2019-08-19) 7 | ++++++++++++++++++ 8 | 9 | * Add proxy support (#20) (by ) 10 | 11 | 2.1.0 (2019-04-25) 12 | ++++++++++++++++++ 13 | 14 | * Send message as file if it is too large 15 | * Fixes in MarkdownFormatter 16 | * Fixes in HTMLFormatter 17 | * Chat id retrieval fixes 18 | * Drop py33 support from tests 19 | * Update setup.py classifiers 20 | * Removed print()-calls in HtmlFormatter (#12) (by Lukas Garberg) 21 | 22 | 23 | 2.0.2 (2017-11-20) 24 | ++++++++++++++++++ 25 | 26 | * fix TypeError in HtmlFormatter.format (by tompipen) 27 | 28 | 29 | 2.0 (2017-03-01) 30 | ++++++++++++++++ 31 | 32 | * Refactored HtmlFormatter and MarkdownFormatter 33 | * Refactored TelegramHandler 34 | * No more need to call a command to obtain a chat_id - it will be obtained automatically on handler init 35 | * Rewritten tests 36 | * Escape LogRecord things in HtmlFormatter 37 | * Added optional emoji symbols in HtmlFormatter. 38 | 39 | 1.1.3 (2016-09-22) 40 | ++++++++++++++++++ 41 | 42 | * Setting escape_message field of StyledFormatter missed (@ihoru) 43 | 44 | 1.1.2 (2016-05-13) 45 | ++++++++++++++++++ 46 | 47 | * Fixed setup.py requires option (changed to install_requires) 48 | 49 | 1.1.1 (2016-04-20) 50 | ++++++++++++++++++ 51 | 52 | * Use HTML Formatter as default formatter for telegram handler 53 | 54 | 1.1.0 (2016-04-20) 55 | ++++++++++++++++++ 56 | 57 | * Introduced HTML Formatter 58 | * Added log text escaping (closed #3) 59 | * Added requests timeout setting (closed #1) 60 | * Catching and logging all requests and their exceptions (closed #2) 61 | 62 | 1.0.0 (2016-04-19) 63 | ++++++++++++++++++ 64 | 65 | * First PyPi release 66 | 67 | 0.1.0 (2016-04-19) 68 | ++++++++++++++++++ 69 | 70 | * Initial release -------------------------------------------------------------------------------- /tests/test_formatters.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import sys 3 | 4 | from telegram_handler import formatters 5 | 6 | 7 | def test_markdown_formatter_exception(): 8 | formatter = formatters.MarkdownFormatter() 9 | 10 | try: 11 | raise ValueError('test') 12 | except ValueError as e: 13 | string = formatter.formatException(sys.exc_info()) 14 | assert string.startswith('```') 15 | assert string.endswith('```') 16 | 17 | 18 | def test_html_formatter_exception(): 19 | formatter = formatters.HtmlFormatter() 20 | 21 | try: 22 | raise ValueError('test') 23 | except ValueError as e: 24 | string = formatter.formatException(sys.exc_info()) 25 | assert string.startswith('
')
26 |         assert string.endswith('
') 27 | 28 | 29 | def test_html_formatter_format(): 30 | formatter = formatters.HtmlFormatter() 31 | 32 | logrecord = logging.makeLogRecord(dict(name='', func='', msg='Whatsup?', funcName='test')) 33 | s = formatter.format(logrecord) 34 | 35 | assert '' not in s 36 | assert '' not in s 37 | 38 | 39 | def test_html_formatter_emoji(): 40 | formatter = formatters.HtmlFormatter(use_emoji=True) 41 | 42 | emoji_level_map = { 43 | formatters.EMOJI.WHITE_CIRCLE: [logging.DEBUG], 44 | formatters.EMOJI.BLUE_CIRCLE: [logging.INFO], 45 | formatters.EMOJI.RED_CIRCLE: [logging.WARNING, logging.ERROR] 46 | } 47 | 48 | for emoji, levels in emoji_level_map.items(): 49 | for level in levels: 50 | logrecord = logging.makeLogRecord({'levelno': level, 'levelname': logging.getLevelName(level)}) 51 | s = formatter.format(logrecord) 52 | assert s.find(emoji) > 0, 'Emoji not found in %s' % level 53 | -------------------------------------------------------------------------------- /telegram_handler/formatters.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from telegram_handler.utils import escape_html 4 | 5 | __all__ = ['TelegramFormatter', 'MarkdownFormatter', 'HtmlFormatter'] 6 | 7 | 8 | class TelegramFormatter(logging.Formatter): 9 | """Base formatter class suitable for use with `TelegramHandler`""" 10 | 11 | fmt = "%(asctime)s %(levelname)s\n[%(name)s:%(funcName)s]\n%(message)s" 12 | parse_mode = None 13 | 14 | def __init__(self, fmt=None, *args, **kwargs): 15 | super(TelegramFormatter, self).__init__(fmt or self.fmt, *args, **kwargs) 16 | 17 | 18 | class MarkdownFormatter(TelegramFormatter): 19 | """Markdown formatter for telegram.""" 20 | fmt = '`%(asctime)s` *%(levelname)s*\n[%(name)s:%(funcName)s]\n%(message)s' 21 | parse_mode = 'Markdown' 22 | 23 | def formatException(self, *args, **kwargs): 24 | string = super(MarkdownFormatter, self).formatException(*args, **kwargs) 25 | return '```\n%s\n```' % string 26 | 27 | 28 | class EMOJI: 29 | WHITE_CIRCLE = '\U000026AA' 30 | BLUE_CIRCLE = '\U0001F535' 31 | RED_CIRCLE = '\U0001F534' 32 | 33 | 34 | class HtmlFormatter(TelegramFormatter): 35 | """HTML formatter for telegram.""" 36 | fmt = '%(asctime)s %(levelname)s\nFrom %(name)s:%(funcName)s\n%(message)s' 37 | parse_mode = 'HTML' 38 | 39 | def __init__(self, *args, **kwargs): 40 | self.use_emoji = kwargs.pop('use_emoji', False) 41 | super(HtmlFormatter, self).__init__(*args, **kwargs) 42 | 43 | def format(self, record): 44 | """ 45 | :param logging.LogRecord record: 46 | """ 47 | super(HtmlFormatter, self).format(record) 48 | 49 | if record.funcName: 50 | record.funcName = escape_html(str(record.funcName)) 51 | if record.name: 52 | record.name = escape_html(str(record.name)) 53 | if record.msg: 54 | record.msg = escape_html(record.getMessage()) 55 | if self.use_emoji: 56 | if record.levelno == logging.DEBUG: 57 | record.levelname += ' ' + EMOJI.WHITE_CIRCLE 58 | elif record.levelno == logging.INFO: 59 | record.levelname += ' ' + EMOJI.BLUE_CIRCLE 60 | else: 61 | record.levelname += ' ' + EMOJI.RED_CIRCLE 62 | 63 | if hasattr(self, '_style'): 64 | return self._style.format(record) 65 | else: 66 | # py2.7 branch 67 | return self._fmt % record.__dict__ 68 | 69 | def formatException(self, *args, **kwargs): 70 | string = super(HtmlFormatter, self).formatException(*args, **kwargs) 71 | return '
%s
' % escape_html(string) 72 | 73 | def formatStack(self, *args, **kwargs): 74 | string = super(HtmlFormatter, self).formatStack(*args, **kwargs) 75 | return '
%s
' % escape_html(string) 76 | -------------------------------------------------------------------------------- /telegram_handler/handlers.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from io import BytesIO 3 | 4 | import requests 5 | 6 | from telegram_handler.formatters import HtmlFormatter 7 | 8 | logger = logging.getLogger(__name__) 9 | logger.setLevel(logging.NOTSET) 10 | logger.propagate = False 11 | 12 | __all__ = ['TelegramHandler'] 13 | 14 | 15 | MAX_MESSAGE_LEN = 4096 16 | 17 | 18 | class TelegramHandler(logging.Handler): 19 | API_ENDPOINT = 'https://api.telegram.org' 20 | last_response = None 21 | 22 | def __init__(self, token, chat_id=None, level=logging.NOTSET, timeout=2, disable_notification=False, 23 | disable_web_page_preview=False, proxies=None): 24 | self.token = token 25 | self.disable_web_page_preview = disable_web_page_preview 26 | self.disable_notification = disable_notification 27 | self.timeout = timeout 28 | self.proxies = proxies 29 | self.chat_id = chat_id or self.get_chat_id() 30 | if not self.chat_id: 31 | level = logging.NOTSET 32 | logger.error('Did not get chat id. Setting handler logging level to NOTSET.') 33 | logger.info('Chat id: %s', self.chat_id) 34 | 35 | super(TelegramHandler, self).__init__(level=level) 36 | 37 | self.setFormatter(HtmlFormatter()) 38 | 39 | @classmethod 40 | def format_url(cls, token, method): 41 | return '%s/bot%s/%s' % (cls.API_ENDPOINT, token, method) 42 | 43 | def get_chat_id(self): 44 | response = self.request('getUpdates') 45 | if not response or not response.get('ok', False): 46 | logger.error('Telegram response is not ok: %s', str(response)) 47 | return 48 | try: 49 | return response['result'][-1]['message']['chat']['id'] 50 | except: 51 | logger.exception('Something went terribly wrong while obtaining chat id') 52 | logger.debug(response) 53 | 54 | def request(self, method, **kwargs): 55 | url = self.format_url(self.token, method) 56 | 57 | kwargs.setdefault('timeout', self.timeout) 58 | kwargs.setdefault('proxies', self.proxies) 59 | response = None 60 | try: 61 | response = requests.post(url, **kwargs) 62 | self.last_response = response 63 | response.raise_for_status() 64 | return response.json() 65 | except: 66 | logger.exception('Error while making POST to %s', url) 67 | logger.debug(str(kwargs)) 68 | if response is not None: 69 | logger.debug(response.content) 70 | 71 | return response 72 | 73 | def send_message(self, text, **kwargs): 74 | data = {'text': text} 75 | data.update(kwargs) 76 | return self.request('sendMessage', json=data) 77 | 78 | def send_document(self, text, document, **kwargs): 79 | data = {'caption': text} 80 | data.update(kwargs) 81 | return self.request('sendDocument', data=data, files={'document': ('traceback.txt', document, 'text/plain')}) 82 | 83 | def emit(self, record): 84 | text = self.format(record) 85 | 86 | data = { 87 | 'chat_id': self.chat_id, 88 | 'disable_web_page_preview': self.disable_web_page_preview, 89 | 'disable_notification': self.disable_notification, 90 | } 91 | 92 | if getattr(self.formatter, 'parse_mode', None): 93 | data['parse_mode'] = self.formatter.parse_mode 94 | 95 | if len(text) < MAX_MESSAGE_LEN: 96 | response = self.send_message(text, **data) 97 | else: 98 | response = self.send_document(text[:1000], document=BytesIO(text.encode()), **data) 99 | 100 | if response and not response.get('ok', False): 101 | logger.warning('Telegram responded with ok=false status! {}'.format(response)) 102 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | python-telegram-handler 2 | *********************** 3 | 4 | .. image:: https://img.shields.io/pypi/status/python-telegram-handler.svg 5 | :target: https://github.com/sashgorokhov/python-telegram-handler 6 | 7 | .. image:: https://img.shields.io/pypi/pyversions/python-telegram-handler.svg 8 | :target: https://pypi.python.org/pypi/python-telegram-handler 9 | 10 | .. image:: https://badge.fury.io/py/python-telegram-handler.svg 11 | :target: https://badge.fury.io/py/python-telegram-handler 12 | 13 | .. image:: https://travis-ci.org/sashgorokhov/python-telegram-handler.svg?branch=master 14 | :target: https://travis-ci.org/sashgorokhov/python-telegram-handler 15 | 16 | .. image:: https://codecov.io/github/sashgorokhov/python-telegram-handler/coverage.svg?branch=master 17 | :target: https://codecov.io/github/sashgorokhov/python-telegram-handler?branch=master 18 | 19 | .. image:: https://codeclimate.com/github/sashgorokhov/python-telegram-handler/badges/gpa.svg 20 | :target: https://codeclimate.com/github/sashgorokhov/python-telegram-handler 21 | :alt: Code Climate 22 | 23 | .. image:: https://img.shields.io/github/license/sashgorokhov/python-telegram-handler.svg 24 | :target: https://raw.githubusercontent.com/sashgorokhov/python-telegram-handler/master/LICENSE 25 | 26 | 27 | A python logging handler that sends logs via Telegram Bot Api 28 | 29 | Installation 30 | ============ 31 | 32 | Via pip: 33 | 34 | .. code-block:: shell 35 | 36 | pip install python-telegram-handler 37 | 38 | Usage 39 | ===== 40 | 41 | Register a new telegram bot and obtain a ``authentication token``. (Instructions here https://core.telegram.org/bots#3-how-do-i-create-a-bot) 42 | 43 | After that, you must obtain a ``chat_id``. You can do that using included simple script. Start a new conversation with newly created bot, write something to it (it is important to initiate conversation first). 44 | 45 | Also, there is an ability for handler to automatically retrieve ``chat_id``. This will be done on handler initialization. But you still have to start a conversation with bot. Be aware: if program stops, server restarts, or something else will happen - handler will try to retrieve chat id from telegram, and may fail, if it will not find a NEW message from you. So i recommend you to use a script below for obtaining chat id. 46 | 47 | Then run a command: 48 | 49 | .. code-block:: shell 50 | 51 | python -m telegram_handler 52 | 53 | If all went ok, a ``chat_id`` will be printed to stdout. 54 | 55 | Using ``token`` and ``chat_id``, configure log handler in your desired way. 56 | For example, using dictConfig: 57 | 58 | .. code-block:: python 59 | 60 | { 61 | 'version': 1, 62 | 'handlers': { 63 | 'telegram': { 64 | 'class': 'telegram_handler.TelegramHandler', 65 | 'token': 'your token', 66 | 'chat_id': 'chat id' 67 | } 68 | }, 69 | 'loggers': { 70 | 'my_logger': { 71 | 'handlers': ['telegram'], 72 | 'level': 'DEBUG' 73 | } 74 | } 75 | } 76 | 77 | Formatting 78 | ========== 79 | 80 | Currently the format of sent messages is very simple: ``%(asctime)s %(levelname)s\nFrom %(name)s:%(funcName)s\n%(message)s`` 81 | Exception traceback will be formatted as pre-formatted fixed-width code block. (https://core.telegram.org/bots/api#html-style) 82 | 83 | If you want to tweak it, configure a ``telegram_handler.HtmlFormatter`` with your desired format string. 84 | Using a dictConfig: 85 | 86 | .. code-block:: python 87 | 88 | ... 89 | { 90 | 'formatters': { 91 | 'telegram': { 92 | 'class': 'telegram_handler.HtmlFormatter', 93 | 'fmt': '%(levelname)s %(message)s' 94 | } 95 | } 96 | 'handlers': { 97 | 'telegram': { 98 | 'class': 'telegram_handler.TelegramHandler', 99 | 'formatter': 'telegram', 100 | 'token': 'your token', 101 | 'chat_id': 'chat id' 102 | } 103 | } 104 | } 105 | ... 106 | 107 | If you wish, you can enable emoji symbols in HtmlFormatter. Just specify `use_emoji=True` in HtmlFormatter settings. 108 | This will add to levelname a :white_circle: for DEBUG, :large_blue_circle: for INFO, and :red_circle: for WARNING and ERROR levels. 109 | 110 | Proxy 111 | =========== 112 | 113 | In case if you have to use this package inside the country where Telegram servers are blocked by gowrnment you can specify proxy urls in config. 114 | Using a dictConfig: 115 | 116 | .. code-block:: python 117 | 118 | ... 119 | { 120 | 'handlers': { 121 | 'telegram': { 122 | 'class': 'telegram_handler.TelegramHandler', 123 | 'formatter': 'telegram', 124 | 'token': 'your token', 125 | 'chat_id': 'chat id', 126 | 'proxies': { 127 | 'http': 'socks5://user:pass@host:port', 128 | 'https': 'socks5://user:pass@host:port' 129 | } 130 | } 131 | } 132 | } 133 | ... 134 | 135 | **Important!** If you plan to use *socks* proxy make sure you have ``requests`` package with ``socks`` support installed: 136 | 137 | .. code-block:: shell 138 | 139 | pip install requests[socks] 140 | -------------------------------------------------------------------------------- /tests/test_handlers.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | 4 | import mock 5 | import pytest 6 | import requests 7 | 8 | import telegram_handler.handlers 9 | 10 | 11 | # From http://stackoverflow.com/questions/899067/how-should-i-verify-a-log-message-when-testing-python-code-under-nose 12 | class MockLoggingHandler(logging.Handler): 13 | """Mock logging handler to check for expected logs. 14 | 15 | Messages are available from an instance's ``messages`` dict, in order, indexed by 16 | a lowercase log level string (e.g., 'debug', 'info', etc.). 17 | """ 18 | 19 | def __init__(self, *args, **kwargs): 20 | self.messages = {'debug': [], 'info': [], 'warning': [], 'error': [], 21 | 'critical': []} 22 | super(MockLoggingHandler, self).__init__(*args, **kwargs) 23 | 24 | def emit(self, record): 25 | "Store a message from ``record`` in the instance's ``messages`` dict." 26 | self.acquire() 27 | try: 28 | name = record.levelname.lower() 29 | self.messages.setdefault(name, []) 30 | self.messages[name].append(record.getMessage()) 31 | finally: 32 | self.release() 33 | 34 | def reset(self): 35 | self.acquire() 36 | try: 37 | for message_list in self.messages.values(): 38 | message_list.clear() 39 | finally: 40 | self.release() 41 | 42 | 43 | @pytest.fixture 44 | def handler(): 45 | handler = telegram_handler.handlers.TelegramHandler('foo', 'bar', level=logging.DEBUG) 46 | telegram_handler.handlers.logger.handlers = [] 47 | telegram_handler.handlers.logger.addHandler(MockLoggingHandler()) 48 | telegram_handler.handlers.logger.level = logging.DEBUG 49 | return handler 50 | 51 | 52 | def test_emit(handler): 53 | record = logging.makeLogRecord({'msg': 'hello'}) 54 | 55 | with mock.patch('requests.post') as patch: 56 | handler.emit(record) 57 | 58 | assert patch.called 59 | assert patch.call_count == 1 60 | assert patch.call_args[1]['json']['chat_id'] == 'bar' 61 | assert 'hello' in patch.call_args[1]['json']['text'] 62 | assert patch.call_args[1]['json']['parse_mode'] == 'HTML' 63 | 64 | def test_emit_big_message(handler): 65 | message = '*' * telegram_handler.handlers.MAX_MESSAGE_LEN 66 | 67 | record = logging.makeLogRecord({'msg': message}) 68 | 69 | with mock.patch('requests.post') as patch: 70 | handler.emit(record) 71 | 72 | assert patch.called 73 | assert patch.call_count == 1 74 | 75 | 76 | def test_emit_http_exception(handler): 77 | record = logging.makeLogRecord({'msg': 'hello'}) 78 | 79 | with mock.patch('requests.post') as patch: 80 | response = requests.Response() 81 | response.status_code = 500 82 | response._content = 'Server error'.encode() 83 | patch.return_value = response 84 | handler.emit(record) 85 | 86 | assert telegram_handler.handlers.logger.handlers[0].messages['error'] 87 | assert telegram_handler.handlers.logger.handlers[0].messages['debug'] 88 | 89 | 90 | def test_emit_telegram_error(handler): 91 | record = logging.makeLogRecord({'msg': 'hello'}) 92 | 93 | with mock.patch('requests.post') as patch: 94 | response = requests.Response() 95 | response.status_code = 200 96 | response._content = json.dumps({'ok': False}).encode() 97 | patch.return_value = response 98 | handler.emit(record) 99 | 100 | assert telegram_handler.handlers.logger.handlers[0].messages['warning'] 101 | 102 | 103 | def test_get_chat_id_success(handler): 104 | with mock.patch('requests.post') as patch: 105 | response = requests.Response() 106 | response.status_code = 200 107 | response._content = json.dumps({'ok': True, 'result': [{'message': {'chat': {'id': 'foo'}}}]}).encode() 108 | patch.return_value = response 109 | 110 | assert handler.get_chat_id() == 'foo' 111 | 112 | 113 | def test_get_chat_id_telegram_error(handler): 114 | with mock.patch('requests.post') as patch: 115 | response = requests.Response() 116 | response.status_code = 200 117 | response._content = json.dumps({'ok': False}).encode() 118 | patch.return_value = response 119 | 120 | assert handler.get_chat_id() is None 121 | 122 | assert telegram_handler.handlers.logger.handlers[0].messages['error'] 123 | 124 | 125 | def test_get_chat_id_no_response(handler): 126 | with mock.patch.object(handler, 'request') as patch: 127 | patch.return_value = None 128 | value = handler.get_chat_id() 129 | 130 | assert value is None 131 | patch.assert_called_once() 132 | 133 | 134 | def test_get_chat_id_response_invalid_format(handler): 135 | with mock.patch('requests.post') as patch: 136 | response = requests.Response() 137 | response.status_code = 200 138 | response._content = json.dumps({'ok': True, 'result': []}).encode() 139 | patch.return_value = response 140 | 141 | assert handler.get_chat_id() is None 142 | 143 | assert telegram_handler.handlers.logger.handlers[0].messages['error'] 144 | assert telegram_handler.handlers.logger.handlers[0].messages['debug'] 145 | 146 | 147 | def test_handler_init_without_chat(): 148 | with mock.patch('requests.post') as patch: 149 | response = requests.Response() 150 | response.status_code = 200 151 | response._content = json.dumps({'ok': False}).encode() 152 | patch.return_value = response 153 | 154 | handler = telegram_handler.handlers.TelegramHandler('foo', level=logging.INFO) 155 | 156 | assert patch.called 157 | assert telegram_handler.handlers.logger.handlers[0].messages['error'] 158 | 159 | assert handler.level == logging.NOTSET 160 | 161 | def test_handler_respects_proxy(): 162 | proxies = { 163 | 'http': 'http_proxy_sample', 164 | 'https': 'https_proxy_sample', 165 | } 166 | 167 | handler = telegram_handler.handlers.TelegramHandler('foo', 'bar', level=logging.INFO, proxies=proxies) 168 | 169 | record = logging.makeLogRecord({'msg': 'hello'}) 170 | 171 | with mock.patch('requests.post') as patch: 172 | handler.emit(record) 173 | 174 | assert patch.call_args[1]['proxies'] == proxies 175 | 176 | def test_custom_formatter(handler): 177 | handler.setFormatter(logging.Formatter()) 178 | 179 | record = logging.makeLogRecord({'msg': 'hello'}) 180 | 181 | with mock.patch('requests.post') as patch: 182 | handler.emit(record) 183 | 184 | assert 'parse_mode' not in patch.call_args[1]['json'] 185 | --------------------------------------------------------------------------------