原创作品:首发u3v3, 转载请保留
作者ID:Yi_Zhi_Yu
首发日期:2017.5.16
Python学习群:278529278 (欢迎交流)
logging 多进程写同一个文件
logging 包的官方文档中明确说过
Although logging is thread-safe, and logging to a single file from multiple threads in a single process is supported, logging to a single file from multiple processes is not supported, because there is no standard way to serialize access to a single file across multiple processes in Python
没有标准的方式让多进程写同一个日志文件
logging 包有一个FileHandler 实现了日志写入文件的操作, 但多进程并发写入时, 会产生数据截断, 覆盖等问题, 下面我们会进行这个实验
同时, 我们也自己简单实现了一个自定义的Handler, 希望能实现多进程并发写入而不会产生FileHandler时的问题, 并进行验证
FileHandler
这是logging包的一个处理模块, 负责将日志消息写入文件, 如果用多进程的方式写入, 会出现什么情况呢,
我们试试
代码如下
def process_log(p_off):
logger_handler = logging.FileHandler('/tmp/one_file_log.log')
logger = logging.getLogger('test')<