1. 配置文件
version: 1
disable_existing_loggers: False
formatters:
simple:
format: "%(asctime)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: logs/info.log
maxBytes: 10485760
backupCount: 20
encoding: utf8
error_file_handler:
class: logging.handlers.RotatingFileHandler
level: ERROR
formatter: simple
filename: logs/errors.log
maxBytes: 10485760
backupCount: 20
encoding: utf8
loggers:
my_module:
level: ERROR
handlers: [info_file_handler]
propagate: no
root:
level: INFO
handlers: [console,info_file_handler,error_file_handler]
2. 应用
import logging.config
import os
def setup_logging(default_path = "logging.yaml", default_level = logging.INFO, env_key = "LOG_CFG"):
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path,"r") as f:
config = yaml.safe_load(f)
logging.config.dictConfig(config)
else:
logging.basicConfig(level = default_level)
setup_logging(default_path = "./logging.yaml")
3. 使用
logger = logging.getLogger(__name__)
logging是单例模式,配置全局有效。