logging模块

1.定义日志对象
#!/bin/python
# -*-coding:utf-8 -*-
"""
@Author : xxxxxx
"""
from typing import Dict
import logging
import logging.config
from logging import LoggerAdapter
"""
LoggerAdapter(logger,extra) 日志加上上下文,即进程用户 进程id等
logging.getLogger(name=None)返回具有指定None的日志记录器
logging.config.dictConfig载入日志配置的字典
"""
# 指定日志格式,之后利用日志对象时可以自定义的东西会写进message,name为定义的日志记录器名字
log_fmt = (
  "%(name)s %(asctime)s %(levelname)s %(process)d %(funcName)s %(lineno)d %(message)s"
)

def log_config(log_level: str, logger_name: str) -> Dict:
  _config = {
    "version":1,
    "disable_existing_loggers": False,
    "formatters":{
      #指定日志格式(“类型1”,“类型2”)
        "json_log_format":{
            "format": log_fmt,
            "class":"pythonjsonlogger.jsonlogger.JsonFormatter",
        }
        "verbose":{ "format": log_fmt,"datefmt":"%Y-%m-%d %H:%M:%SZ"},
    },
      "filters": {},
      "handers":{
        # 处理器(“自定义处理器名字”:“log类型 控制台流文件-文件”, “formater格式”:“json/verbose”,filename:“./xxxx.log”)
        "console":{"class":"logging.StreamHandler","formatter":"verbose"},
        "file_hander":{"class":"logging.FileHandler","formatter":"json_log_format","filename":"./xxxxx.log"},
        "json_console":{"class":"logging.StreamHandler","formatter":"json_log_format"}
    },
      "loggers":{
        #使用定义的logger_name 
        logger_name:{
           #选择上面的logger_name
            "handlers":["ffile_hander", "json_console"}],
            "level": log_level,
             "propagate": False
        }
      },
  }
  return _config


def get_config(logger_name: str = "my_log_name", log_level: str = "INFO",) -> LoggerAdapter
    logging.config.dictConfig(log_config(log_level,logger_name))
    return LoggerAdapter(logging.getLogger(logger_name),{})

logger = get_logger()
2.使用日志对象
from xxx import logger
# 写进message
logger.info("xxxxxxxx")
logger.error("xxxxxxxx")

你可能感兴趣的:(logging模块)