python中以json格式输出log日志

本文介绍了如何在Python中利用logging模块将日志信息以JSON格式进行输出,从而方便后期处理和分析。

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})
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值