python中以json格式输出log日志
import json
import logging
import datetime
import socket
class HostIp:
host_name = None
host_ip = None
@classmethod
def get_host_ip(cls):
if not cls.host_name or not HostIp.host_ip:
try:
cls.host_name = socket.gethostname()
cls.host_ip = socket.gethostbyname(cls.host_name)
except ConnectionError:
cls.host_name = "unknown hostname"
cls.host_ip = "unknown ip"
return cls.host_name, cls.host_ip
REMOVE_ATTR = ["filename", "module", "exc_text", "stack_info", "created", "msecs", "relativeCreated", "exc_info", "msg",
"args", "name", "levelname", "levelno", "pathname", "lineno", "funcName", "thread", "threadName",
"processName", "process"]
class JSONFormatter(logging.Formatter):
host_name, host_ip = HostIp.get_host_ip()
@classmethod
def build_record(cls, record):
return {attr_name: record.__dict__[attr_name] for attr_name in record.__dict__ if attr_name not in REMOVE_ATTR}
@classmethod
def set_format_time(cls, msg_dict):
now = datetime.datetime.now()
format_time = now.strftime("%Y-%m-%dT%H:%M:%S" + ".%03d" % (now.microsecond / 1000))
msg_dict['@timestap'] = format_time
return format_time
@classmethod
def set_host_ip(cls, msg_dict):
msg_dict['host_name'] = JSONFormatter.host_name
msg_dict['host_ip'] = JSONFormatter.host_ip
def format(self, record):
msg_dict = self.build_record(record)
self.set_format_time(msg_dict) # set time
self.set_host_ip(msg_dict) # set host name and host ip
if isinstance(record.msg, dict):
msg_dict['msg'] = record.msg # set message
else:
if record.args:
msg_dict['msg'] = "'" + record.msg + "'," + str(record.args).strip('()')
else:
msg_dict['msg'] = record.msg
if record.exc_info:
msg_dict['exc_info'] = self.formatException(record.exc_info)
if self._fmt == 'pretty':
return json.dumps(msg_dict, indent=2, ensure_ascii=False) # indent 非负整型,输出json数据前面显示的空白符的个数,这样输出的json数据也叫pretty-printed
else:
return json.dumps(msg_dict, ensure_ascii=False) # ensure_ascii,默认值为True,非ASCII码字符显示为\uXXX序列,设置为False时,存入json的中文可正常显示
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
handler_console = logging.StreamHandler()
# 设置级别
handler_console.setLevel(logging.INFO)
# 设置格式
handler_console.setFormatter(JSONFormatter('pretty'))
log.addHandler(handler_console)
def logger(msg):
try:
log.info(msg)
except Exception:
log.exception({"exception_id": 22000})
if __name__ == '__main__':
# logger({'a':1})
logger({'a': '1', 'b': '2', 'c': '3', 'd': '4','e':5})