Last active
August 29, 2015 14:00
-
-
Save KyleJamesWalker/11189456 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import json | |
import logging | |
import logging.handlers | |
import requests | |
class BufferingSlackWebHookHandler(logging.handlers.BufferingHandler): | |
def __init__(self, capacity, organization, token, | |
channel=None, username=None, icon_url=None, icon_emoji=None): | |
if icon_emoji and icon_url: | |
raise ValueError("Error: Cannot set icon_emoji and icon_url.") | |
logging.handlers.BufferingHandler.__init__(self, capacity) | |
self.web_hook_url = "https://{}.slack.com/services/hooks/" \ | |
"incoming-webhook?token={}".format(organization, token) | |
self._payload = {} | |
if channel: | |
self._payload['channel'] = channel | |
if username: | |
self._payload['username'] = username | |
if icon_emoji: | |
self._payload['icon_emoji'] = icon_emoji | |
elif icon_url: | |
self._payload['icon_url'] = icon_url | |
def flush(self): | |
self.acquire() | |
try: | |
# Send Messages to slack | |
if len(self.buffer): | |
#Load Message as an attachment. | |
self._payload['attachments'] = [{ | |
"color": "#36a64f", | |
"fallback": "Python Logger Attachment. *Expandable*", | |
"fallback": "Python Logger Attachment.", | |
"text": "\n".join( | |
[self.format(x).replace(r'\n', '\n') | |
for x in self.buffer] | |
), | |
}] | |
# Clear buffer before posting with requests. | |
# Note: requests can add to the logger, if configured. | |
self.buffer = [] | |
requests.post(self.web_hook_url, | |
data=json.dumps(self._payload)) | |
except: | |
self.handleError(None) | |
finally: | |
self.release() | |
if __name__ == "__main__": | |
logger = logging.getLogger(__name__) | |
logger.setLevel(logging.DEBUG) | |
bswh = BufferingSlackWebHookHandler(100, | |
"your_slack_org", | |
"api_key_here", | |
"#sample-channel", | |
"PythonLogging", | |
icon_emoji=':bar_chart:') | |
formatter = logging.Formatter( | |
"%(asctime)s %(levelname) 8s(%(name)s): %(message)s") | |
bswh.setFormatter(formatter) | |
logger.addHandler(bswh) | |
for i in xrange(110): | |
test = "Lots of Lines!!!" | |
logger.info(test) | |
logging.shutdown() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Optional Change To split on carriage returns:
"fields": [{'value': x} for z in self.buffer for y in self.format(z).split('\n') for x in y.split('\n')]