import logging import logging.handlers import os import time #调用方法 例如:import LogPackagecopy(该脚本文件名称) logs=LogPackagecopy.Logger(filename='1.txt',path=None) logs.Log()或 logs=LogPackagecopy.Logger(filename='1.txt',path=1,driver_path=os.getcwd()) logs.Log() #logger=logging.getLogger(__name__) LEVELS = {'NOSET': logging.NOTSET, 'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARNING': logging.WARNING, 'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL} class Logger(object): def __init__(self,filename=None,path=None,driver_path=None): self.filename=filename self.path=path self.driver_path=driver_path def Log(self): if self.path==None: if os.path.isfile(self.filename): pass else: with open(self.filename,'wb')as file: pass self.rotatingFileHandler = logging.handlers.RotatingFileHandler(self.path+'\\'+self.filename, maxBytes = 1024 * 1024 * 50, backupCount = 5) elif self.path==1: self.path=os.path.join(self.driver_path,'logs') if os.path.join(self.path)and os.path.isdir(self.path): if os.path.isfile(os.path.join(self.path,self.filename)): pass else: with open(self.path+'\\'+self.filename,'wb')as file: pass pass else: os.mkdir(self.path) with open(self.path+'\\'+self.filename,'wb')as file: pass self.rotatingFileHandler = logging.handlers.RotatingFileHandler(self.path+'\\'+self.filename, maxBytes = 1024 * 1024 * 50, backupCount = 5) #define a rotating file handler #定义一个RotatingFileHandler,最多备份5个日志文件,每个日志文件最大50M # rotatingFileHandler = logging.handlers.RotatingFileHandler(self.path+'\\'+self.filename, # maxBytes = 1024 * 1024 * 50, # backupCount = 5) self.formatter = logging.Formatter("%(asctime)s %(name)-12s %(levelname)-8s %(message)s") self.rotatingFileHandler.setFormatter(self.formatter) logging.getLogger("").addHandler(self.rotatingFileHandler) #define a handler whitch writes messages to sys self.console = logging.StreamHandler() self.console.setLevel(logging.NOTSET) #set a format which is simple for console use self.formatter = logging.Formatter("%(asctime)s %(name)-12s: %(levelname)-8s %(message)s") #tell the handler to use this format self.console.setFormatter(self.formatter) #add the handler to the root logger logging.getLogger("").addHandler(self.console) # set initial log level self.logger = logging.getLogger("") self.logger.setLevel(logging.NOTSET) if __name__=='__main__': pass
日志封装
猜你喜欢
转载自blog.csdn.net/lssrain/article/details/80423745
今日推荐
周排行