V
V
Vampre2020-08-20 15:29:32
Python
Vampre, 2020-08-20 15:29:32

How to correctly use QueueHandler to send logs to telegram?

Let's say I use QueueHandler to send logs to telegram:

import logging
from logging.handlers import QueueHandler, QueueListener
from queue import Queue
import requests

class TgHandler(QueueHandler):
    def __init__(self):
        self.queue = Queue(-1)
        super().__init__(self.queue)
        self.handler = MessageHandler()
        self.listener = QueueListener(self.queue, self.handler)
        self.listener.start()

class MessageHandler(logging.Handler):
    api_url = 'https://api.telegram.org/botmy-token/sendMessage'
    chat_id = 123

    def emit(self, record):
        message = self.format(record)
        params = {
            'chat_id': self.chat_id,
            'text': message
        }
        requests.post(self.api_url, json=params)


But I ran into such a problem that sending messages does not occur because when the main thread ends, it does not wait until the code in the thread with the MessageHandler is executed:
import logging
from logging.config import dictConfig

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'telegram': {
            'class': 'my_logger.TgHandler',
            'level': 'INFO',
        },
    },
    'loggers': {
        'telegram': {
            'handlers': ['telegram'],
            'level': 'INFO',
        }
    }
}

dictConfig(LOGGING)

logger = logging.getLogger('telegram')

try:
    1/0
except ZeroDivisionError as e:
    logger.exception(e, stack_info=True)
    # import time; time.sleep(5) - а вот так все работает 

print('Done!')


Is there any possibility to change this behavior, or am I doing something wrong in general...?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2020-08-20
@Vampre

On the one hand, if your application lives for more than 5 seconds, your logs will still work - you can score.
On the other hand, crashes will definitely not get into the logs: in order to get there, you need to wait for the processing of all messages in the queue

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question