Search code examples
pythonloggingevent-handlingslack

Creating a custom slack log handler doesn't work


I want to create a custom python logging Handler to send messages via slack.

I found this package however its no longer being updated so i created a very bare bone version of it. however it doesnt seem to work, I added a print call for debugging purposes and emit is not being evoked.

import logging
# import slacker

class SlackerLogHandler(logging.Handler):
    def __init__(self, api_key, channel):
        super().__init__()
        self.channel = channel
        # self.slacker = slacker.Slacker(api_key)

    def emit(self, record):
        message = self.format(record)
        print('works')
        # self.slacker.chat.post_message(text=message, channel=self.channel)

slack_handler = SlackerLogHandler('token', 'channel')
slack_handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
slack_handler.setFormatter(formatter)

logger = logging.getLogger('my_app')
logger.addHandler(slack_handler)
logger.info('info_try')  # 'works' is not printed and no slack message is sent

I saw this answer and tried to also inherit from StreamHandler but to no avail.

I think I am missing something very basic.

edited to remove slack logic for ease of reproduction.


Solution

  • After some additional searching I found out that the logging level that is set for the handler is separate from the level that is set for the logger.

    meaning, that adding:

    logger.setLevel(logging.INFO)
    

    fixes the problem.