Answer the question
In order to leave comments, you need to log in
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)
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!')
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question