Skip to content

Instantly share code, notes, and snippets.

@johnwheeler
Last active July 11, 2017 11:52
Show Gist options
  • Save johnwheeler/0fce845f49061265854d to your computer and use it in GitHub Desktop.
Save johnwheeler/0fce845f49061265854d to your computer and use it in GitHub Desktop.
Python Logstash Formatter compatible with json codec format
import logging
import json
class LogstashFormatter(logging.Formatter):
def __init__(self, fmt=None, datefmt='%Y-%m-%dT%H:%M:%SZ'):
super(LogstashFormatter, self).__init__(fmt, datefmt)
def format(self, record):
obj = record.__dict__.copy()
obj['@timestamp'] = self.formatTime(record, self.datefmt)
obj['message'] = super(LogstashFormatter, self).format(record)
obj.pop('msg')
return json.dumps(obj)
@johnwheeler
Copy link
Author

My take on a LogstashFormatter for python. Use it like:

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.propagate = False
logger.handlers = []
handler = logging.StreamHandler()
formatter = LogstashFormatter(fmt="%(levelname)s - %(asctime)s %(filename)s:%(lineno)d %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment