码迷,mamicode.com
首页 > 编程语言 > 详细

python 日志 logging模块

时间:2021-04-24 13:26:40      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:handlers   info   ==   get   targe   图片   ror   ext   ogg   

背景

使用print,无法打印日志的级别错误,故用logging模块

彩色打印

import logging
# logger = logging.getLogger(‘your-module‘)
# Initialize coloredlogs.
import coloredlogs
coloredlogs.install(level=‘DEBUG‘)

logging.basicConfig(level = logging.INFO,format = ‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)
logger = logging.getLogger(__name__)
 
logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")

技术图片

通过JSON文件配置

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":{
        "my_module":{
            "level":"ERROR",
            "handlers":["info_file_handler"],
            "propagate":"no"
        }
    },
    "root":{
        "level":"INFO",
        "handlers":["console","info_file_handler","error_file_handler"]
    }
}

通过JSON加载配置文件,然后通过logging.dictConfig配置logging,

import json
import logging.config
import os

def setup_logging(default_path = "logging_config.json",info_file=‘info.log‘,errors_file=‘errors.log‘,default_level = logging.INFO,env_key = "LOG_CFG"):
  path = default_path
  value = os.getenv(env_key,None)
  config = None
  if value:
    path = value
  if os.path.exists(path):
    with open(path,"r") as f:  
      config = json.load(f)
    if config:
      config[‘handlers‘][‘info_file_handler‘][‘filename‘] = info_file
      config[‘handlers‘][‘error_file_handler‘][‘filename‘] = errors_file
      with open(path,"w") as f:
        json.dump(config, f)
      print(‘config---‘,config)
      with open(path,"r") as f:
        config = json.load(f)
        logging.config.dictConfig(config)
  else:
    logging.basicConfig(level = default_level)
 
def func():
  logging.info("start func")

  logging.warning("exec func")

  logging.info("end func")
 
if __name__ == "__main__":
  setup_logging(info_file=‘a.log‘,errors_file=‘e.log‘)
  func()

后期info_file和errors_file可配置使用

参考

(4条消息) python 日志 logging模块(详细解析)_pansaky的博客-CSDN博客]

python 日志 logging模块

标签:handlers   info   ==   get   targe   图片   ror   ext   ogg   

原文地址:https://www.cnblogs.com/ministep/p/14695264.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!