Skip to content

Instantly share code, notes, and snippets.

@FulcronZ
Created July 19, 2016 04:57
Show Gist options
  • Save FulcronZ/c57ea4c3cc4a4e5631c83e3442c225a2 to your computer and use it in GitHub Desktop.
Save FulcronZ/c57ea4c3cc4a4e5631c83e3442c225a2 to your computer and use it in GitHub Desktop.
Python JSON Logging Formatter
"""
MIT License
Copyright (c) 2016 Pipat Methavanitpong
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import sys
import logging
import json
class DictFormatter(logging.Formatter):
"""
DictFormatter performs string interpolation on a LogRecord.msg dict.
If LogRecord.msg is not dict type, it returns an empty dict {}.
DictFormatter does not accept a string format. It accepts only datefmt.
All attributes in logging.Formatter can be used.
In addition, %(exc_text)s attribute is available. %(exc_text)s provides
exception information.
%(message)s attribute is a string representation of LogRecord.msg dict.
"""
def __init__(self, datefmt=None):
self.datefmt = datefmt
def format(self, record):
record.message = record.getMessage()
if isinstance(record.msg, dict):
return self._dictformat(record)
elif isinstance(record.msg, basestring):
return {}
def _dictformat(self, record):
d = record.msg.copy()
record.asctime = self.formatTime(record, self.datefmt)
if record.exc_info:
if not record.exc_text:
record.exc_text = self.formatException(record.exc_info)
if not record.exc_text:
record.exc_text = ""
for k, v in d.iteritems():
d[k] = d[k] % record.__dict__
return d
class JSONFormatter(DictFormatter):
def __init__(self, datefmt=None):
DictFormatter.__init__(self, datefmt)
def format(self, record):
message = DictFormatter.format(self, record)
return json.dumps(message, indent=4)
hostname = 'iot.eclipse.org'
topic = 'orgID/appName/clusterID/deviceID/'
# Create and configure a logger instance
logger = logging.getLogger('')
myHandler = logging.StreamHandler(sys.stdout)
myHandler.setLevel(logging.INFO)
myHandler.setFormatter(JSONFormatter(datefmt='%m/%d/%Y %I:%M:%S %p'))
logger.addHandler(myHandler)
# Test logging from all log levels
logger.debug({ "time" : "%(asctime)s", "msg" : "a debug message" })
logger.info({ "time" : "%(asctime)s", "msg" : "an info message" })
logger.warning({ "time" : "%(asctime)s", "msg" : "a warning message" })
logger.warning({ "time" : "%(asctime)s", "msg" : "%(msg)s" })
logger.warning("a warning message")
logger.error({ "time" : "%(asctime)s", "msg" : "an error message" })
logger.critical({ "time" : "%(asctime)s", "msg" : "a critical message" })
try:
raise Exception("an exception message")
except Exception as error:
logger.exception({ "time" : "%(asctime)s", "msg" : "%(exc_text)s" })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment