令人震惊的大坑

您所在的位置:网站首页 增大硬盘内存以前的内容会被删除吗 令人震惊的大坑

令人震惊的大坑

2024-07-03 06:29| 来源: 网络整理| 查看: 265

前言:最近写测试框架遇到了一个磁盘内存不足的问题,问题是多进程往同一个日志文件中写日志,由于我设置了日志文件大小,所以会面临不同进程对同一个文件进行读写,句柄泄漏导致磁盘空间无法释放,机器的磁盘被占满,在此记录一下解决办法。 遇到这个问题的时候我百度了一番,参考了两位博主的文章解决了问题: 1、博主一 2、博主二

logging官方文档介绍如下:

Because there is no standard way to serialize access to a single file across multiple processes in Python. If you need to log to a single file from multiple processes, one way of doing this is to have all the processes log to a SocketHandler, and have a separate process which implements a socket server which reads from the socket and logs to file. (If you prefer, you can dedicate one thread in one of the existing processes to perform this function.)

意识是说:logging 是线程安全的,也就是说,在一个进程内的多个线程同时往同一个文件写日志是安全的。但是多个进程往同一个文件写日志不是安全的。

有的人会说,那我不用多进程不就可以了。但是 Python 有一个 GIL 的大锁,使用多线程是没法利用到多核 CPU 的,大部分情况下会改用多进程来利用多核 CPU,因此我们还是绕不开不开多进程下日志的问题。

为了解决这个问题,可以使用 ConcurrentLogHandler,ConcurrentLogHandler 可以在多进程环境下安全的将日志写入到同一个文件,并且可以在日志文件达到特定大小时,分割日志文件。在默认的 logging 模块中,有个 TimedRotatingFileHandler 类,可以按时间分割日志文件,可惜 ConcurrentLogHandler 不支持这种按时间分割日志文件的方式。

用法如下:

import sys import os import logging from concurrent_log_handler import ConcurrentRotatingFileHandler from datetime import timedelta sys.path.append('..') # 日志记录(目前为了进程安全采用的是ConcurrentRotatingFileHandler方法,无法按照日期切割) def make_dir(make_dir_path): path = make_dir_path.strip() if not os.path.exists(path): os.makedirs(path) return path log_dir_name = "logs" log_file_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) + os.sep + log_dir_name make_dir(log_file_folder) logging.basicConfig(level=logging.DEBUG) # 安照日志文件大小切割,超过1M时切割,最多保留10个日志文件 fileHandler = ConcurrentRotatingFileHandler("logs/dadi-api-auto.log", encoding='utf-8', maxBytes=1024 * 1024, backupCount=10) fileHandler.setLevel('DEBUG') logging_format = logging.Formatter( "[%(asctime)s][%(levelname)s][%(filename)s:%(funcName)s:%(lineno)s] - %(message)s") fileHandler.setFormatter(logging_format) app.logger.addHandler(fileHandler)

运行后可以发现,会自动创建一个.lock文件,通过锁的方式来安全的写日志文件。 在这里插入图片描述



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3