1、yml 配置文件配置
如上图所示,注意用于指定自定义的 filter 类的 key 是 () 而不是 class,详情请看官方文档说明:官方文档说明,斜体部分内容摘自官方文档:
The schema supports user-defined objects for handlers, filters and formatters. (Loggers do not need to have different types for different instances, so there is no support in this configuration schema for user-defined logger classes.)
Objects to be configured are described by dictionaries which detail their configuration. In some places, the logging system will be able to infer from the context how an object is to be instantiated, but when a user-defined object is to be instantiated, the system will not know how to do this. In order to provide complete flexibility for user-defined object instantiation, the user needs to provide a ‘factory’ - a callable which is called with a configuration dictionary and which returns the instantiated object. This is signalled by an absolute import path to the factory being made available under the special key ‘()’.
2、自定义配置读取函数读取 yml 配置文件内容并加载
def load_logging():
cur_dir = os.path.dirname(os.path.realpath(__file__))
conf_file = os.path.join(cur_dir, 'logging.yml')
with open(conf_file, "r") as f:
config = yaml.load(f, yaml.SafeLoader)
config['handlers']['info_file_handler']['filename'] = os.path.join(cur_dir, 'lego.log')
logging.config.dictConfig(config)
如上面代码段所示,把 yml 配置文件的内容读取到一个 dict 类型的变量之后使用 lgging.config.dictConfig(存储yml文件内容的变量) 加载变量中存储的配置,如果配置项需要更改的话可以通过更改变量中的内容来实现。
附(yml 配置文件示例):
disable_existing_loggers: False
formatters:
simple:
format: "%(asctime)s - %(process)d - %(processName)s - %(thread)d - %(threadName)s - %(levelname)s - %(message)s"
filters:
step_filter:
# https://docs.python.org/3.5/library/logging.config.html#logging-config-dict-connections
# () 指定对应的自定义类
(): conf.logging_loader.StepsFilter
name: root
handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: simple
stream: ext://sys.stdout
info_file_handler:
class: concurrent_log_handler.ConcurrentRotatingFileHandler
level: INFO
formatter: simple
filename: lego.log
maxBytes: 10485760
backupCount: 20
encoding: utf8
database_handler:
class: conf.logging_loader.DataBaseHandler
level: INFO
formatter: simple
filters: [step_filter]
root:
level: INFO
# handlers: [console,info_file_handler,database_handler]
handlers: [console,database_handler]