脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python logging模块的分文件存放详析

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

2022-07-16 09:56hqx Python

这篇文章主要介绍了python logging模块的分文件存放详析,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下

前言:

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

异常信息:

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

解决方法:

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

代码实现:customer_log.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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

?
1
2
3
4
from customer_log imoprt set_basic_logger
import mu
set_basic_logger()
mu.show_cur_info()

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

?
1
2
3
4
5
import logging
def show_cur_info():
    msg = 'dddddd'
    print(msg)
    logging.info(msg

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

原文链接:https://blog.csdn.net/qq_17328759/article/details/125793689

延伸 · 阅读

精彩推荐