python 日志器(直接用)

2022年1月10日15:59:18 发表评论 457 views

使用方法如下(可定义多个python logger):

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')
        formatter = logging.Formatter('时间:%(asctime)s,'
                                      '日志级别:%(levelname)s,'
                                      '日志错误行:%(lineno)d,'
                                      '调用错误的函数:%(funcName)s'
                                      '日志内容:%(message)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__':
    pass

    # log = Log('loged', log_path)
#     # loged = log.Logger
#     # log2 = Log('printlog', print_log_path)
#     # print_log = log2.Logger

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: