Python基于yaml文件配置logging日志过程解析

阳光穿透心脏的1/2处 2022-12-27 01:51 311阅读 0赞

更多编程教程请到:菜鸟教程 https://www.piaodoo.com/

友情链接:

高州阳光论坛https://www.hnthzk.com/

人人影视http://www.op-kg.com/

一、使用logging.config.dictConfig()函数读取配置信息,参数是字典类型

  1. with open(file="./loggingconfigyaml.yaml", mode='r', encoding="utf-8")as file:
  2. logging_yaml = yaml.load(stream=file, Loader=yaml.FullLoader)
  3. # print(logging_yaml)
  4. # 配置logging日志:主要从文件中读取handler的配置、formatter(格式化日志样式)、logger记录器的配置
  5. logging.config.dictConfig(config=logging_yaml)
  6. # 获取根记录器:配置信息从yaml文件中获取
  7. root = logging.getLogger()
  8. # 子记录器的名字与配置文件中loggers字段内的保持一致
  9. my_module = logging.getLogger("my_module")
  10. print("rootlogger:", root.handlers)
  11. print("selflogger", my_module.handlers)
  12. # print("子记录器与根记录器的handler是否相同:", root.handlers[0] == my_module.handlers[0])
  13. my_module.error("DUBUG")
  14. root.info("INFO")
  15. root.error('ERROR')
  16. root.debug("rootDEBUG")

二、详细看一下yaml配置文件

  1. version: 1
  2. # 将信息传播到配置文件的跟日志记录器中
  3. disable_existing_loggers: False

formatters:
simple:
format: “%(asctime)s - %(filename)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 # 10MB
backupCount: 20
encoding: utf8

error_file_handler:

  1. # class: logging.handlers.RotatingFileHandler
  2. # level: ERROR
  3. # formatter: simple
  4. # filename: ./info.log
  5. # maxBytes: 10485760 # 10MB
  6. # backupCount: 20
  7. # encoding: utf8

loggers:
my_module:
level: ERROR
handlers: [console]
# 打开日志记录器
propagate: False
root:
level: DEBUG
handlers: [console, info_file_handler]

说明:

1、formatters配置了日志格式化输出时的样式;handlers配置了需要处理的日志信息,例如日志输出的位置(class字段,logging模块的handler只有streamhandler和filehandler,剩下的handler在logging.handlers模块中)、处理程序需要处理的日志级别(level字段),日志输出样式(formatter)等。

2、loggers设置了自定义的logger实例,在程序中使用logging.getLogger(“名字与配置文件中的logger名字一致且是字符串形式”)函数获取配置文件中logger实例的配置信息,例如打印的日志级别、子记录器的handler(1:子记录器与根记录器有相同的handler时,打印输出的日志会出现两遍,2:记录器的handler有多个时,而且输出的位置相同且class字段相同,也会导致输出两遍;诸如此问题,将logger记录器的propagate属性设置为False,就会禁止将日志消息传递给父级记录器的处理程序中)等;root设置了根记录器的配置信息,例如打印的日志级别、记录器的handler(多个handler时用列表存储)等

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持菜鸟教程www.piaodoo.com。

发表评论

表情:
评论列表 (有 0 条评论,311人围观)

还没有评论,来说两句吧...

相关阅读

    相关 MySQL日志文件

    前言 在MySQL服务器运行过程中,除了会产生各种数据文件外,还会记录各种日志文件,这些日志文件不仅仅记录MySQL的数据库的运行情况、用户操作、错误信息等,还和MySQ