yaml
今天用yaml文件写了一下logging的配置,文件如下:
version: 1
disable_existing_loggers: False
formatters:
simple:
format: "%(asctime)s - %(filename)s - %(levelname)s - %(message)s"
handlers:
console:
class: logging.StreamHandler
level: ERROR
formatter: simple
stream: ext://sys.stdout
info_file_handler:
class: logging.handlers.RotatingFileHandler
level: INFO
formatter: simple
filename: ./mylog/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: [console]
propagate: no
root:
level: INFO
handlers: [console, info_file_handler]
只是做个demo,所以写的比较粗略,然后中间就是包含了formatter,handlers,并没有使用filters,最终的效果是ERROR级别的信息将会在命令台进行打印并写入日志文件当中。
try_log.py
# -*- coding: utf-8 -*-
import os
import yaml
import logging
from logging import config as logger_config
config_file = os.path.join(os.path.dirname(__file__), "config.yaml")
if os.path.exists("mylog"):
pass
else:
os.mkdir("mylog")
with open(config_file, "rt") as stream:
config = yaml.unsafe_load(stream.read())
logger_config.dictConfig(config)
logger = logging.getLogger()
if __name__ == "__main__":
logger.error("This is a test error message for my first logger.")
运行这个命令就可以看到相应的结果了。