|
| 1 | +""" |
| 2 | +Most of this Slack logging is pulled from here: |
| 3 | + https://github.com/junhwi/python-slack-logger/ |
| 4 | +""" |
| 5 | +import os |
| 6 | +import logging |
| 7 | +import json |
| 8 | + |
| 9 | +from logging import LogRecord |
| 10 | +from urllib.parse import urlparse |
| 11 | +from logging.handlers import HTTPHandler |
| 12 | + |
| 13 | + |
| 14 | +class SlackHandler(HTTPHandler): |
| 15 | + def __init__(self, url, username=None, icon_url=None, icon_emoji=None, channel=None, mention=None): |
| 16 | + o = urlparse(url) |
| 17 | + is_secure = o.scheme == 'https' |
| 18 | + HTTPHandler.__init__(self, o.netloc, o.path, method="POST", secure=is_secure) |
| 19 | + self.username = username |
| 20 | + self.icon_url = icon_url |
| 21 | + self.icon_emoji = icon_emoji |
| 22 | + self.channel = channel |
| 23 | + self.mention = mention and mention.lstrip('@') |
| 24 | + |
| 25 | + def mapLogRecord(self, record): |
| 26 | + text = self.format(record) |
| 27 | + |
| 28 | + if isinstance(self.formatter, SlackFormatter): |
| 29 | + payload = { |
| 30 | + 'attachments': [ |
| 31 | + text, |
| 32 | + ], |
| 33 | + } |
| 34 | + if self.mention: |
| 35 | + payload['text'] = '<@{0}>'.format(self.mention) |
| 36 | + else: |
| 37 | + if self.mention: |
| 38 | + text = '<@{0}> {1}'.format(self.mention, text) |
| 39 | + payload = { |
| 40 | + 'text': text, |
| 41 | + } |
| 42 | + |
| 43 | + if self.username: |
| 44 | + payload['username'] = self.username |
| 45 | + if self.icon_url: |
| 46 | + payload['icon_url'] = self.icon_url |
| 47 | + if self.icon_emoji: |
| 48 | + payload['icon_emoji'] = self.icon_emoji |
| 49 | + if self.channel: |
| 50 | + payload['channel'] = self.channel |
| 51 | + |
| 52 | + ret = { |
| 53 | + 'payload': json.dumps(payload), |
| 54 | + } |
| 55 | + return ret |
| 56 | + |
| 57 | + |
| 58 | +class SlackFormatter(logging.Formatter): |
| 59 | + def format(self, record): |
| 60 | + ret = {} |
| 61 | + if record.levelname == 'INFO': |
| 62 | + ret['color'] = 'good' |
| 63 | + elif record.levelname == 'WARNING': |
| 64 | + ret['color'] = 'warning' |
| 65 | + elif record.levelname == 'ERROR': |
| 66 | + ret['color'] = '#E91E63' |
| 67 | + elif record.levelname == 'CRITICAL': |
| 68 | + ret['color'] = 'danger' |
| 69 | + |
| 70 | + ret['author_name'] = record.levelname |
| 71 | + ret['title'] = record.name |
| 72 | + ret['ts'] = record.created |
| 73 | + ret['text'] = super(SlackFormatter, self).format(record) |
| 74 | + return ret |
| 75 | + |
| 76 | + |
| 77 | +class SlackLogFilter(logging.Filter): |
| 78 | + """ |
| 79 | + Logging filter to decide when logging to Slack is requested, using |
| 80 | + the `extra` kwargs: |
| 81 | + `logger.info("...", extra={'notify_slack': True})` |
| 82 | + """ |
| 83 | + |
| 84 | + def filter(self, record): |
| 85 | + return getattr(record, 'notify_slack', False) |
| 86 | + |
| 87 | + |
| 88 | +class CkcSlackHandler(SlackHandler): |
| 89 | + """ |
| 90 | + Override the default handler to insert our own URL |
| 91 | + """ |
| 92 | + def __init__(self, **kwargs): |
| 93 | + url = os.getenv('SLACK_WEBHOOK_URL') |
| 94 | + super().__init__(url, **kwargs) |
| 95 | + |
| 96 | + def format(self, record: LogRecord) -> str: |
| 97 | + """Surround our log message in a "code block" for styling.""" |
| 98 | + return f"```{super().format(record)}```" |
0 commit comments