Skip to content

Instantly share code, notes, and snippets.

@vagonzalez
Last active August 29, 2015 14:13
Show Gist options
  • Save vagonzalez/1a8a89a461c6c14d3eb7 to your computer and use it in GitHub Desktop.
Save vagonzalez/1a8a89a461c6c14d3eb7 to your computer and use it in GitHub Desktop.

This is a log handler that can be used to send messages to HipChat.

The HipChat room, token and sender should be set in the standard Django settings.py file as part of the logging setup. The required settings 'token' and 'room' can be found / set in the Admin section of HipChat.com (you will need a registered account to use HipChat).

"""
Custom log handler for posting log messages to HipChat.
The API documentation is available at https://www.hipchat.com/docs/api/method/rooms/message
The room id can be found by going to https://{{your-account}}.hipchat.com/rooms/ids
The tokens can be set at https://{{your-account}}.hipchat.com/admin/api
Dependencies: Requests (http://docs.python-requests.org)
"""
import sys
import requests
import logging
from logging import Handler, INFO, DEBUG, WARN, WARNING, ERROR, CRITICAL
class HipChatHandler(Handler):
"""
Log handler used to send notifications to HipChat
"""
HIPCHAT_API_URL = 'https://api.hipchat.com/v1/rooms/message'
def __init__(self, token, room,
sender='Django', notify=False, color='yellow', colors={}):
"""
:param token: the auth token for access to the API - see hipchat.com
:param room: the numerical id of the room to send the message to
:param sender (optional): the 'from' property of the message - appears in the HipChat window
:param notify (optional): if True, HipChat pings / bleeps / flashes when message is received
:param color (optional): sets the background color of the message in the HipChat window
:param colors (optional): a dict of level:color pairs (e.g. {'DEBUG:'red'} used to
override the default color)
"""
Handler.__init__(self)
self.token = token
self.room = room
self.sender = sender
self.notify = notify
self.color = color
self.colors = colors
def emit(self, record):
"""
Sends the record info to HipChat
"""
if not self.token:
return
try:
notify = self.notify
# use a custom level-based color from self.colors, if it exists in the dict
color = self.colors.get(record.levelname,self.color)
r = self._sendToHipChat(record.getMessage(),color, notify)
# use print, not logging, as that would introduce a circular reference
print 'Message sent to room {0}: {1}\nResponse: {2}'.format(
self.room, record.getMessage(),r.text)
except:
print sys.exc_info()[1]
self.handleError(record)
def _sendToHipChat(self, msg, color, notify):
"""
Does the actual sending of the message.
"""
payload = {'auth_token':self.token,
'notify':notify,
'color':color,
'from':self.sender,
'room_id':self.room,
'message':msg
}
r = requests.post(self.HIPCHAT_API_URL, msg, params=payload)
return r
# sample Django logging configuration for HipChat logger.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'hipchat': {
'level': 'INFO',
'class': 'log_handler.HipChatHandler',
'token': '{{your_token_here}}',
'room' : '{{your_room_id_here}}',
'sender': 'Django app',
'notify': True,
'color':'green',
'colors': {
'ERROR':'red',
'CRITICAL':'red',
'WARNING':'yellow',
}
}
},
'loggers': {
'test_handler': {
'handlers': ['hipchat'],
'level': 'INFO',
'propagate': False,
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment