对python日志logging进行类封装

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()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Pythonlogging模块可以用来记录程序运行时的日志信息,包括调试信息、警告信息、错误信息等。为了方便使用,可以对logging模块进行封装,使其更容易调用和管理。 以下是一些可能有用的封装方法: 1. 封装基本配置:将logging模块的基本配置封装成一个函数,可以方便地进行调用和修改。例如: ```python import logging def init_logger(log_file): logger = logging.getLogger() logger.setLevel(logging.DEBUG) handler = logging.FileHandler(log_file) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) ``` 这个函数会初始化一个logger对象,并将其级别设置为DEBUG,将日志输出到指定的文件中,并使用指定的格式进行格式化。 2. 封装消息型:可以定义不同的消息型,例如debug、info、warning、error等,然后为每种型都定义一个封装函数,以简化调用。例如: ```python import logging logger = logging.getLogger() def debug(msg): logger.debug(msg) def info(msg): logger.info(msg) def warning(msg): logger.warning(msg) def error(msg): logger.error(msg) ``` 这样,使用时可以直接调用对应的函数,例如: ```python debug('this is a debug message') warning('this is a warning message') ``` 3. 封装上下文信息:有时候需要在日志中添加一些上下文信息,例如当前时间、请求参数、用户ID等。可以定义一个上下文管理器,用with语句来管理上下文信息的输出。例如: ```python import logging logger = logging.getLogger() class LogContext: def __init__(self, **kwargs): self.kwargs = kwargs def __enter__(self): logger.info('start context', extra=self.kwargs) def __exit__(self, exc_type, exc_value, traceback): logger.info('end context', extra=self.kwargs) ``` 使用时可以这样调用: ```python with LogContext(user_id=123): logger.info('do something') ``` 这样会在日志中输出一条包含上下文信息的记录。 总之,封装logging模块可以帮助我们更方便地使用日志功能,提高开发效率和代码可维护性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值