python logging模块怎么分文件存放(logging,python,开发技术)

时间:2024-04-29 23:27:15 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

前言:

如果使用进到的日志文件方法:logging.FileHandler,会导致日志信息全部存放在一个日志文件中,不利于后面对日志文件的使用。
下面分享常见的两种分文件存储日志的方法。
delay = True 参数避免了出现多进程中读取日志权限的问题

TimedRotatingFileHandler 根据时间创建日志文件

TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None)

python logging模块怎么分文件存放

atTime 与 when参数之间的关系

python logging模块怎么分文件存放

RotatingFileHander 根据日志文件大小创建日志文件

RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False)

python logging模块怎么分文件存放

分文件时,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模块怎么分文件存放的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:vue之ele多级联组件如何使用下一篇:

10 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18