python logging模块的分文件存放详析

前言:

如果使用进到的日志文件方法: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异常处理

异常信息:

--- Logging error --- Traceback (most recent call last): '省略部分信息' PermissionError: [WinError 32] 另一个程序正在使用此文件,进程无法访问。

解决方法:

设置 delay=True使用第三方库 concurrent_log_handler.ConcurrentRotatingFileHandler

代码实现:customer_log.py

import logging from logging import handlers from concurrent_log_handler import ConcurrentRotatingFileHandler def set_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)s line:%(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)s line:%(lineno)d [%(levelname)s] : %(message)s', handlers=[handler, err_handler] )

在项目主程序中使用时:main.py

from customer_log imoprt set_basic_logger import mu set_basic_logger() mu.show_cur_info()

在项目其他模块使用时:mu.py

import logging def show_cur_info(): msg = 'dddddd' print(msg) logging.info(msg

到此这篇关于python logging模块的分文件存放详析的文章就介绍到这了,更多相关python logging模块内容请搜索易知道(ezd.cc)以前的文章或继续浏览下面的相关文章希望大家以后多多支持易知道(ezd.cc)!

推荐阅读