yaml文件是python中比较常用的一种配置文件

yaml文件:

version: 1
# 将信息传播到配置文件的根日志记录器中
disable-exiting-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: DEBUG
formatter: simple
filename: ../log/info.log
maxBytes: 10485760 # 10MB
backupCount: 20
encoding: utf8

# error_file_handler:
# class: logging.handlers.RotatingFileHandler
# level: ERROR
# formatter: simple
# filename: ../log/info.log
# maxBytes: 10485760 # 10MB
# backupCount: 20
# encoding: utf8

#loggers:
# normal:
# level: ERROR
# handlers: [ console ]

root:
level: DEBUG
handlers: [ console, info_file_handler ]

python调用

import logging.config
import time

import yaml
from utils.file_util import FileUtil


class LogUtil(object):
def __init__(self):
self.root_path = FileUtil().get_root_path()
with open(file=self.root_path + 'config\\yaml\\log.yaml', mode='r', encoding='utf-8') as f:
self.log_yaml = yaml.load(stream=f, Loader=yaml.FullLoader)
# 根据日期生成文件名称
file = time.strftime('%Y%m%d', time.localtime(time.time())) + '.log'
self.log_yaml['handlers']['info_file_handler']['filename'] = FileUtil().get_root_path() + 'log\\' + file

def m_get_logger(self):
logging.config.dictConfig(self.log_yaml)
m_log = logging.getLogger()
return m_log


if __name__ == '__main__':
LogUtil().m_get_logger().debug('debug')
LogUtil().m_get_logger().error('error')
LogUtil().m_get_logger().critical('critical')

运行结果

python通过yaml文件配置日志_配置文件