概述
之前写的自定义日志器存在不完善,现在进行自定义日志器优化:
- 读取yaml日志配置文件
- 更改日志配置路径
- 使用logging.config.dictConfig配置日志
- 获取Logger进行使用
代码展示
yaml日志配置文件
# version must be 1
# logger配置文件
#########################################logging yaml profile##################################################
version: 1
disable_existing_loggers: False
formatters:
simple:
format: "%(asctime)s - %(thread)s - [%(levelname)s] %(pathname)s - %(funcName)s : %(message)s"
#filters:
handlers:
info_file_timedRotatingFileHandler:
class: logging.handlers.TimedRotatingFileHandler
level: INFO
formatter: simple
filename: autoRunner.log
when: 'midnight'
backupCount: 20
encoding: utf8
error_file_timedRotatingFileHandler:
class: logging.handlers.TimedRotatingFileHandler
level: ERROR
formatter: simple
filename: autoRunner_error.log
when: 'midnight'
backupCount: 20
encoding: utf8
warn_file_timedRotatingFileHandler:
class: logging.handlers.TimedRotatingFileHandler
level: WARN
formatter: simple
filename: autoRunner_warn.log
when: 'midnight'
backupCount: 20
encoding: utf8
root:
level: INFO
handlers: [info_file_timedRotatingFileHandler,error_file_timedRotatingFileHandler,warn_file_timedRotatingFileHandler]
自定义日志类
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author : holidaylzz
# Time : 2020/7/13
import os
import yaml.scanner
import logging
from logging.config import dictConfig
from autoRunner.utils.path_utils import pathUtil
# DEFAULT_LOG_CONFIG_PATH = PathUtils().get_project_abspath('autoRunner', 'conf', 'logging.yml')
DEFAULT_LOG_CONFIG_PATH = os.path.join(pathUtil.rootPath, 'autoRunner','conf', 'logging.yml')
DEFAULT_LOG_PATH = pathUtil.get_project_abspath('log')
DEFAULT_LOG_NAME = 'autoRunner.log'
class LogUtils(object):
def __init__(self, logger_name, config_path=DEFAULT_LOG_CONFIG_PATH, log_path=DEFAULT_LOG_PATH, log_name=DEFAULT_LOG_NAME):
"""
:param logger_name:
:param config_path:
:param log_path:
:param log_name:
"""
# 新建日志文件目录,一定要新建这个目录否则会FileNotFoundError
os.makedirs(log_path, exist_ok=True)
# read logging.yml
with open(config_path, 'rt') as file:
config = yaml.safe_load(file.read())
# 遍历logging.yml文件字典的handlers,修改filename
for handler, handler_value in config['handlers'].items():
if handler_value['level'] == 'INFO':
handler_value['filename'] = os.path.join(log_path, log_name)
continue
if handler_value['level'] == 'ERROR':
# 通过切片找到errorlog
handler_value['filename'] = os.path.join(log_path, f'{log_name[:-4]}_error.log')
continue
if handler_value['level'] == 'WARN':
# 通过切片找到warnlog
handler_value['filename'] = os.path.join(log_path, f'{log_name[:-4]}_warn.log')
continue
# 配置logging
logging.config.dictConfig(config)
self.__logger = logging.getLogger(logger_name)
@property
def logger(self):
return self.__logger
if __name__ == '__main__':
log = LogUtils('AAA').logger
try:
d = 1/0
except Exception as e:
log.exception('error --->>> %s', e)
输出:
生成3个level的日志文件
最后
以上就是直率海燕为你收集整理的python dictConfig封装自定义日志器(二)代码展示的全部内容,希望文章能够帮你解决python dictConfig封装自定义日志器(二)代码展示所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复