对python日志logging进行类封装

对python日志logging进行类封装,第1张

python logging模块的四大组件:日志器、处理器、过滤器、格式器。

# coding = utf-8

import logging
import time
from function import project_path


class FrameLog:
    def __init__(self):
        #创建日志器
        self.logger = logging.getLogger()
        # 设置日志输出级别
        self.logger.setLevel(level=logging.DEBUG)
        # 设置日志路径以及日志文件名
        self.log_time = time.strftime('%Y_%m_%d %H_%M_%S')
        self.log_path = project_path() + '\Logs/'
        self.log_name = self.log_path + self.log_time + 'log.log'
        self.format = logging.Formatter(fmt='%(asctime)s %(filename)s %(lineno)d %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S %a')

    def set_filehandler(self):
        # 创建文件处理器
        self.file_handler = logging.FileHandler(self.log_name, mode='a', encoding='utf-8')
        # 处理器设置日志输出级别
        self.file_handler.setLevel(logging.INFO)
        # 处理器添加格式器
        self.file_handler.setFormatter(self.format)
        # 日志器添加文件处理器
        self.logger.addHandler(self.file_handler)
        # 关闭打开的文件
        self.file_handler.close()

    def log(self):
        self.set_filehandler()
        # 返回日志器
        return self.logger


if __name__ == '__main__':
    log = FrameLog().log()
    log.info('info')
    log.error('error')
    log.debug('debug')
    log.warning('warning')
    log.critical('严重级别')

    from selenium import webdriver

    driver = webdriver.Chrome()
    baidu_url = 'https://www.baidu.com/'
    log.info('开始打开百度{}'.format(baidu_url))
    driver.get(baidu_url)
    log.info('关闭浏览器')
    driver.quit()

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/715110.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-25
下一篇 2022-04-25

发表评论

登录后才能评论

评论列表(0条)

保存