例如:让debug, info,warning,error函数都允许传递一个trace_id, 并将这个trace_id输出到我们自定义日志指定的格式中。
import logging
import inspect
import logging.config
self_logger = logging.getLogger("debug")
class Logger(logging.Logger):
@staticmethod
def check_trace_id(kwargs):
"""kwargs mush has trace_id and trace_id value type mush is str."""
trace_id = str(kwargs.get("trace_id", ""))
if "extra" not in kwargs:
extra = {"trace_id": trace_id}
else:
assert isinstance(kwargs["extra"], dict)
extra = kwargs["extra"]
extra.update({"trace_id": trace_id})
if "trace_id" in kwargs.keys():
kwargs.pop("trace_id")
return extra, kwargs
def debug(self, msg, *args, **kwargs):
extra, kwargs = self.check_trace_id(kwargs)
self_logger.debug(msg, *args, extra=extra, **kwargs)
def info(self, msg, *args, **kwargs):
extra, kwargs = self.check_trace_id(kwargs)
self_logger.info(msg, *args, extra=extra, **kwargs)
def warning(self, msg, *args, **kwargs):
extra, kwargs = self.check_trace_id(kwargs)
self_logger.warning(msg, *args, extra=extra, **kwargs)
def error(self, msg, *args, **kwargs):
extra, kwargs = self.check_trace_id(kwargs)
self_logger.error(msg, *args, extra=extra, **kwargs)
logger = Logger()
def init_log(log_path, log_name, log_level="DEBUG"):
log_level = log_level.upper()
LOG_PATH_DEBUG = "%s/%s.log" % (log_path, log_name)
LOG_FILE_BACKUP_COUNT = 10
log_conf = {
"version": 1,
"formatters": {
"format1": {
"format": '|%(asctime)s.%(msecs)03d|%(levelname)s|%(trace_id)s|%(thread)d|%(filename)s %(lineno)d|%(message)s',
"datefmt": '%Y-%m-%d %H:%M:%S',
},
},
"handlers": {
"handler": {
"class": "logging.handlers.TimedRotatingFileHandler",
"level": log_level,
"formatter": "format1",
"when": "midnight",
"backupCount": LOG_FILE_BACKUP_COUNT,
"filename": LOG_PATH_DEBUG
},
},
"loggers": {
"debug": {
"handlers": ["handler"],
"level": log_level
},
}
}
logging.config.dictConfig(log_conf)
def close_log():
logging.shutdown()