Skip to content

Instantly share code, notes, and snippets.

@iamsilvio
Created May 13, 2013 14:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamsilvio/5568540 to your computer and use it in GitHub Desktop.
Save iamsilvio/5568540 to your computer and use it in GitHub Desktop.
a loggingHandler for Python to send notifications via the Prowl API
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
class ProwlHandler(logging.Handler):
"""
A handler class which sends a Prowl notification for each logging event.
"""
priority_map = {
"DEBUG": -2,
"INFO": -1,
"WARNING": 0,
"ERROR": 1,
"CRITICAL": 2
}
API_URL = 'https://api.prowlapp.com/publicapi/add'
def mapPriority(self, levelName):
"""
Default value of 0 if not provided.
An integer value ranging [-2, 2] representing:
Very Low = -2
Moderate = -1
Normal = 0
High = 1
Emergency = 2
Emergency priority messages may bypass quiet hours
according to the user's settings.
"""
return self.priority_map.get(levelName)
def __init__(self, apikey, applicationName):
"""
Initialize the handler.
"""
if not apikey:
raise ValueError("apikey is not optional")
self.apikey = apikey
self.application = applicationName
logging.Handler.__init__(self)
def emit(self, record):
"""
Emit a record.
Format the record and send it
"""
try:
import urllib
import urllib2
req = urllib2.Request(self.API_URL)
data = {'apikey': self.apikey,
'application': self.application,
'event': record.levelname.lower(),
'description': self.format(record),
'priority': self.mapPriority(record.levelname)}
req.add_data(urllib.urlencode(data))
urllib2.urlopen(req)
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment