python3通过json文件配置日志

1) logging.json配置如下:

{
    "version":1,
    "disable_existing_loggers":false,
    "formatters":{
        "simple":{
            "format":"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        }
    },
    "handlers":{
        "console":{
            "class":"logging.StreamHandler",
            "level":"DEBUG",
            "formatter":"simple",
            "stream":"ext://sys.stdout"
        },
        "info_file_handler":{
            "class":"logging.handlers.RotatingFileHandler",
            "level":"INFO",
            "formatter":"simple",
            "filename":"info.log",
            "maxBytes":10485760,
            "backupCount":20,
            "encoding":"utf8"
        },
        "error_file_handler":{
            "class":"logging.handlers.RotatingFileHandler",
            "level":"ERROR",
            "formatter":"simple",
            "filename":"errors.log",
            "maxBytes":10485760,
            "backupCount":20,
            "encoding":"utf8"
        }
    },
    "loggers":{
        "": { ---root默认,模块名找不到则使用
            "level":"INFO",
            "handlers":["console","info_file_handler","error_file_handler"],
            "propagate":false ---重复日志
        },
        "module1":{ ---模块名
            "level":"INFO",
            "handlers":["console","info_file_handler","error_file_handler"],
            "propagate":false
        },
        "module2":{ ---模块名
            "level":"INFO",
            "handlers":["console","info_file_handler","error_file_handler"],
            "propagate":false
        }
    }
}

2) 初始化

def setup_logging(default_path = "logging.json", default_level = logging.INFO, env_key = "LOG_CFG"):

    path = default_path

    value = os.getenv(env_key, None)

    if value:

        path = value

    if os.path.exists(path):

        with open(path,"r") as f:

            config = json.load(f)

            logging.config.dictConfig(config)

    else:

        logging.basicConfig(level = default_level)

3)使用

kgLogger = logging.getLogger("module1")

kgLogger = logging.getLogger("abc") --调用默认配置

kgLogger.info("This is for test!")

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值