-
-
Save neilalbrock/2654206 to your computer and use it in GitHub Desktop.
RedisHandler for Python stdlib logging
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
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