作者:E4b9a6, 创建:2021-06-16, 字数:1331, 已阅:71, 最后更新:2021-06-16
logging 支持YAML格式的日志配置文件,在项目入口main文件同一层添加logging.yaml文件,内容如下
version: 1
formatters:
common:
format: "%(asctime)s - %(levelname)s - %(threadName)s - %(message)s"
datefmt: "%Y/%m/%d %H:%M:%S"
console:
format: "%(asctime)s - %(levelname)s - %(pathname)s - %(message)s"
datefmt: "%Y/%m/%d %H:%M:%S"
handlers:
# 不同会输出大于等于此级别的信息
common:
class: logging.handlers.TimedRotatingFileHandler
formatter: common
level: INFO
when: D
interval: 1
encoding: utf8
filename: "logs/running.log"
# suffix: "%Y-%m-%d.log"
# 日志保留个数
backupCount: 7
console:
class : logging.StreamHandler
formatter: console
level : INFO
stream : ext://sys.stdout
loggers:
main.common:
level: INFO
handlers: [common]
# 如果模块中没有使用 如logging.getLogger('main.common') 这样的配置来获取loggers中对应的配置,则默认会使用下面的root配置
root:
level: DEBUG
handlers: [console]
在main文件配置logging模块
import os
import yaml
import logging
import logging.config
os.chdir(os.path.abspath(os.path.dirname(os.path.abspath(__file__))))
# Logger config
if not os.path.exists('logs'):
os.mkdir('logs')
# 日志配置
with open('logging.yaml', 'r', encoding='utf-8') as f:
config = yaml.load(f, Loader=yaml.FullLoader)
logging.config.dictConfig(config)
logger = logging.getLogger('main.common')