两种方法实现python操作日志的封装

方法1

import logging

class Log(object):
    def __init__(self, name=__name__, path=‘mylog.log‘, level=‘DEBUG‘):
        self.__name = name
        self.__path = path
        self.__level = level
        self.__logger = logging.getLogger(self.__name)
        self.__logger.setLevel(self.__level)

    def __ini_handler(self):
        """初始化handler"""
        stream_handler = logging.StreamHandler()
        file_handler = logging.FileHandler(self.__path, encoding=‘utf-8‘)
        return stream_handler, file_handler

    def __set_handler(self, stream_handler, file_handler, level=‘DEBUG‘):
        """设置handler级别并添加到logger收集器"""
        stream_handler.setLevel(level)
        file_handler.setLevel(level)
        self.__logger.addHandler(stream_handler)
        self.__logger.addHandler(file_handler)

    def __set_formatter(self, stream_handler, file_handler):
        """设置日志输出格式"""
        formatter = logging.Formatter(‘%(asctime)s-%(name)s-%(filename)s-[line:%(lineno)d]‘
                                      ‘-%(levelname)s-[日志信息]: %(message)s‘,
                                      datefmt=‘%a, %d %b %Y %H:%M:%S‘)
        stream_handler.setFormatter(formatter)
        file_handler.setFormatter(formatter)

    def __close_handler(self, stream_handler, file_handler):
        """关闭handler"""
        stream_handler.close()
        file_handler.close()

    @property
    def Logger(self):
        """构造收集器,返回looger"""
        stream_handler, file_handler = self.__ini_handler()
        self.__set_handler(stream_handler, file_handler)
        self.__set_formatter(stream_handler, file_handler)
        self.__close_handler(stream_handler, file_handler)
        return self.__logger

if __name__ == ‘__main__‘:
    log = Log(__name__, ‘file.log‘)
    logger = log.Logger
    logger.debug(‘I am a debug message‘)
    logger.info(‘I am a info message‘)
    logger.warning(‘I am a warning message‘)
    logger.error(‘I am a error message‘)
    logger.critical(‘I am a critical message‘)

初始化方法参数说明

  • name:自定义日志的名字, 默认是root, 但是我这里是使用调用文件的__name__ 作为默认名字

  • path:生成的日志的文件名

  • level:日志的级别,我这里把所有的级别都默认设置了level=DEBUG

方法2

使用logging.fileconfig这个模块实现(不知道这个模块的找度娘恶补一下把)

1.使用配置文件构造日志配置信息

logger.ini

[loggers]
keys = root, example01, example02
[logger_root]
level = DEBUG
handlers = hand01, hand02
[logger_example01]
handlers = hand01, hand02
qualname = example01
propagate = 0
[logger_example02]
handlers = hand01, hand03
qualname = example02
propagate = 0
[handlers]
keys = hand01, hand02, hand03
[handler_hand01]
class = StreamHandler
level = INFO
formatter = form01
args=(sys.stdout, )
[handler_hand02]
class = FileHandler
level = DEBUG
formatter = form01
args = (‘log/test_case_log.log‘, ‘a‘)
[handler_hand03]
class = handlers.RotatingFileHandler
level = INFO
formatter = form01
args = (‘log/test_case_log.log‘, ‘a‘, 10*1024*1024,3)
[formatters]
keys = form01, form02
[formatter_form01]
format = %(asctime)s-%(filename)s-[line:%(lineno)d]-%(levelname)s-[LogInfoMessage]: %(message)s
datefmt = %a, %d %b %Y %H:%M:%S
[formatter_form02]
format = %(name)-12s: %(levelname)-8s-[日志信息]: %(message)s
datefmt = %a, %d %b %Y %H:%M:%S

封装python代码

import logging
from logging import config


class MyLog(object):

    def __init__(self):
        config.fileConfig(‘logger.ini‘)
        self.logger = logging.getLogger(‘example01‘)

    @property
    def my_logger(self):

        return self.logger

if __name__ == ‘__main__‘:
    log = MyLog()
    log.my_logger.info(‘it is my test log message info‘)

两种方法各有好处吧

第一种代码很好理解思路清晰 , 但是不利于项目都维护,比如日志文件名,日志格式等无法修改,只能通过代码内部修改

第二种其实是使用config模块内部使用配置文件操作模块ConfigParser做了封装, 用配置文件来构造自定义日志器,好处很明显,我们只要通过修改配置文件就能修改日志的格式,名字,级别等等一些设置,无需改动代码,而且使用很简单, 其实这种方法完全不需要封装一个python代码,哪个模块需要输出日志,直接调用config模块获得logger就可以了(就是上面文件的那几行代码

相关推荐