一、yaml的安装:
pip install pyyaml
二、yaml配置文件的创建:
创建文件时以.yaml后缀名结束或者以.yml后缀名结束
三、yaml文件例子
1、字典
log:
logger_name: "python"
logger_level: "DEBUG"
stream_level: "DEBUG"
file_level: "INFO"
filepath: "pythonlog.txt"
2、列表
study:
- hello
- world
- python
注:冒号后面要记得加空格(logger_name:空格"python")
四、yaml文件封装
import yaml
#读取yaml配置文件
def read_yaml(filepath):
with open(filepath,encoding="utf-8") as f:
conf=yaml.load(f,Loader=yaml.SafeLoader)
return conf
#写入数据到yaml配置文件
def write_yaml(filepath,data):
with open(filepath,"a",encoding="utf-8") as f:
yaml.dump(data,f)
#调试本程序
if __name__ =="__main__":
con=read_yaml("config.yaml")
print(con)
write_yaml("config.yaml","testdata")
五、使用yaml封装日志记录
import logging
"""
使用yaml封装日志记录
"""
#导入已封装的读取yaml配置文件的函数
from study_yaml.yaml_handle import read_yaml
conf=read_yaml("config.yaml")
logconf=conf["log"] #如果未将conf["log"]赋值,则下面的参数需要写成logger_name=conf["log"]["logger_name"]
def record_logging(logger_name=logconf["logger_name"],logger_level=logconf["logger_level"],stream_level=logconf["stream_level"],file_level=logconf["file_level"],filepath=logconf["filepath"]):
# 初始化收集器
logger = logging.getLogger(logger_name)
logger.setLevel(logger_level)
# 初始化处理器,输出日志到控制台
stream_handle = logging.StreamHandler()
stream_handle.setLevel(stream_level)
# 将处理器添加到收集器里
logger.addHandler(stream_handle)
# 设置输出日志格式,包括时间,报错的文件名,行号,错误等级及错误信息
fm = logging.Formatter("%(asctime)s---%(filename)s---%(lineno)d---%(levelname)s---%(message)s")
stream_handle.setFormatter(fm)
# 如果文件路径不为空,就输出日志到文本文件
if filepath:
# 初始化处理器,输出日志到文本文件
file_handle = logging.FileHandler(filepath, encoding="UTF-8")
file_handle.setLevel(file_level)
file_handle.setFormatter(fm)
logger.addHandler(file_handle)
return logger
if __name__ == '__main__':
logger = record_logging() #不传参按照默认的执行
# logger=record_logging(stream_level="ERROR",file_level="CRITICAL",filepath="log.txt")
logger.debug("debug信息")
logger.info("info信息")
logger.warning("warning信息")
logger.error("error信息")
logger.critical("critical信息")