# Passing a custom parameter through a logger

I have a custom logger which logs all messages at WARNING level and above to a Slack channel. Certain error messages occur so frequently that they make it hard to see actual errors in the channel, so I would like to be able to disable Slack logging for a specific message, using something like logger.error("This is a common error", slack=False).

The following approach works, but I was wondering if there is a nicer way to do it. One downside of this approach is that if any code that isn't using my custom logger uses the slack=False argument then it will cause an exception.

def get_slack_logger():
logger = logging.getLogger("slack_logger")
logger.setLevel(logging.DEBUG)

# Add other handlers like stderr and log file.
# ...

class SlackHandler(logging.Handler):
def __init__(self):
super().__init__(self)

def emit(self, record):
if not record.slack:
return
# Actually send the contents of record.message to a Slack channel.
# ...

slack_handler = SlackHandler()
slack_handler.setLevel(logging.WARNING)

# Wrap logger in an adapter that handles the slack argument.
def __init__(self, logger, extra={}):
super().__init__(logger, extra)

def process(self, msg, kwargs):
extra = kwargs.get("extra", {})
extra.update({"slack": kwargs.pop("slack", True)})
kwargs["extra"] = extra
return (msg, kwargs)


• I don't think I can achieve the same effect using a filter can I? The Logger will throw an exception on the slack argument. – DanielGibbs Jan 14 '17 at 19:19
• @DanielGibbs: You wouldn't need the slack argument if you had a filter. – Gareth Rees Jan 14 '17 at 21:43