python logging模块怎么分文件存放
导读:本文共2151.5字符,通常情况下阅读需要7分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 前言:如果使用进到的日志文件方法:logging.FileHandler,会导致日志信息全部存放在一个日志文件中,不利于后面对日志文件的使用。下面分享常见的两种分文件存储日志的方法。delay = True 参数避免了出现多进程中读取日志权限的问题TimedRotatingFileHandler 根据时间创建日志文件TimedRotatingFileHandle... ...
目录
(为您整理了一些要点),点击可以直达。前言:
如果使用进到的日志文件方法:logging.FileHandler
,会导致日志信息全部存放在一个日志文件中,不利于后面对日志文件的使用。
下面分享常见的两种分文件存储日志的方法。delay = True
参数避免了出现多进程中读取日志权限的问题
TimedRotatingFileHandler 根据时间创建日志文件
TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None)
atTime 与 when参数之间的关系
RotatingFileHander 根据日志文件大小创建日志文件
RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False)
分文件时,PermissionError异常处理
异常信息:
---Loggingerror---Traceback(mostrecentcalllast):'省略部分信息'PermissionError:[WinError32]另一个程序正在使用此文件,进程无法访问。
解决方法:
设置 delay=True
使用第三方库 concurrent_log_handler.ConcurrentRotatingFileHandler
代码实现:customer_log.py
importloggingfromloggingimporthandlersfromconcurrent_log_handlerimportConcurrentRotatingFileHandlerdefset_basic_logger():path=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))log_path=path+'/Log/'log_file=log_path+'mockSystem.log'err_file=log_path+'mockSystemErr.log'#定制输出格式formatter=logging.Formatter('[%(asctime)s]%(filename)s->%(funcName)sline:%(lineno)d[%(levelname)s]:%(message)s')##所有日志在一个文件中存储#handler=logging.FileHandler(log_file,encoding='utf-8',mode='a+')#按天分文件存储,保存最近30天的日志handler=handlers.TimedRotatingFileHandler(log_file,when='d',interval=1,backupCount=30,encoding='utf-8',delay=True)#按文件大小分文件存储,每个文件10字节,保留10个文件#handler=handlers.RotatingFileHandler(log_file,maxBytes=10,backupCount=10,#encoding='utf-8',delay=True)#按文件大小分文件存储,每个文件10字节,保留10个文件#handler=ConcurrentRotatingFileHandler(log_file,maxBytes=10,backupCount=10)handler.setLevel(logging.INFO)handler.setFormatter(formatter)#err_handler=ConcurrentRotatingFileHandler(err_file,encoding='utf-8',mode='a+')#输出到err_log文件err_handler=handlers.TimedRotatingFileHandler(err_file,when='d',interval=1,backupCount=30,encoding='utf-8',delay=True)#err_handler=handlers.RotatingFileHandler(err_file,maxBytes=10,backupCount=10,#encoding='utf-8',delay=True)#err_handler=ConcurrentRotatingFileHandler(err_file,maxBytes=10,backupCount=10)err_handler.setLevel(logging.WARNING)err_handler.setFormatter(formatter)logging.basicConfig(level=logging.DEBUG,format='[%(asctime)s]%(filename)s->%(funcName)sline:%(lineno)d[%(levelname)s]:%(message)s',handlers=[handler,err_handler])
在项目主程序中使用时:main.py
fromcustomer_logimoprtset_basic_loggerimportmuset_basic_logger()mu.show_cur_info()
在项目其他模块使用时:mu.py
importloggingdefshow_cur_info(): msg='dddddd' print(msg) logging.info(msg
</div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
python logging模块怎么分文件存放的详细内容,希望对您有所帮助,信息来源于网络。