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.")
運行這個命令就可以看到相應的結果了。