import logging
class Logger:
def __init__(self, stream=None, cmd_lever=logging.WARNING, file_level=logging.DEBUG, logname='mylog'):
self.stream = stream
self.cmd_lever = cmd_lever
self.file_level = file_level
# 实例化记录器
self.logger = logging.getLogger(logname)
self.logger.setLevel(logging.DEBUG)
# 设置Format的格式
self.cmd_Format = logging.Formatter('%(message)s')
self.file_Format = logging.Formatter('%(message)s')
def cmd_log(self, logname='mylog'):
# 处理器的格式
self.cmdHandler = logging.StreamHandler(self.stream)
# 设置处理器的等级
self.cmdHandler.setLevel(self.cmd_lever)
# 处理器绑定 Format 的格式
self.cmdHandler.setFormatter(self.cmd_Format)
# 记录器绑定处理器
self.logger.addHandler(self.cmdHandler)
# 关闭处理器防止重复
self.cmdHandler.close()
# 设置过滤器
FIL = logging.Filter(logname)
# 过滤器绑定记录器
self.logger.addFilter(FIL)
def file_log(self, path):
# 处理器的格式
self.fileHandler = logging.FileHandler(path)
# 设置处理器的等级
self.fileHandler.setLevel(self.file_level)
# 处理器绑定 Format 的格式
self.fileHandler.setFormatter(self.file_Format)
# 记录器绑定处理器
self.logger.addHandler(self.fileHandler)
# 关闭处理器防止重复
self.fileHandler.close()
logger = Logger().logger
标签:logging,模块,Format,self,处理器,file,日志,logger
From: https://www.cnblogs.com/duanfu456/p/17227291.html