Skip to content

Instantly share code, notes, and snippets.

@hellp
Last active October 3, 2015 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hellp/2428204 to your computer and use it in GitHub Desktop.
Save hellp/2428204 to your computer and use it in GitHub Desktop.
RedisHandler for Python stdlib logging
import logging
import redis # http://pypi.python.org/pypi/redis
class RedisHandler(logging.Handler):
def __init__(self, lname, conn, *args, **kwargs):
logging.Handler.__init__(self, *args, **kwargs)
self.lname = lname
self.channel = lname + ":chan"
self.redis_conn = conn
def emit(self, record):
msg = self.format(record)
try:
self.redis_conn.pipeline()\
.publish(self.channel, msg)\
.rpush(self.lname, msg)\
.ltrim(self.lname, -1000, -1)\ # keep only the last 1000 log entries
.execute()
except redis.RedisError:
pass
# Usage example
if __name__ == '__main__':
import socket
host = socket.gethostname().split('.')[0]
fmt = '%(asctime)s {0} %(name)s %(levelname)s %(message)s'.format(host)
logging.basicConfig(format=fmt, level=logging.INFO)
logger = logging.getLogger(__name__)
handler = RedisHandler('foolog', redis.StrictRedis('redis.example.com'))
handler.setFormatter(logging.Formatter(fmt))
logger.addHandler(handler)
logger.info('Logger set up.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment