Python中多进程Gunicorn的日志为什么不会错乱?
我的 flask 项目使用 logging 模块,使用 TimedRotatingFileHandler,然后 gunicorn 开了 32 个进程.
logging 模块不是进程安全的,这个 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.)
但是我的项目跑了半年,从来没有看到日志错乱的情况,每一条都清清楚楚..
Google 了下,搜到了一个 gunicorn 的 issue:https://github.com/benoitc/gunicorn/issues/1272
但是看完了这个 issue 表示还是云里雾里没懂,gunicorn 作者给的解释如下
The fd is shared between all workers, and until it isn't over the limit (depending on your system) alls logs will go over it.
求详细解释,谢谢
Python中多进程Gunicorn的日志为什么不会错乱?
因为子进程共享了父进程的文件句柄
Gunicorn的多进程日志不乱,主要是因为它的日志系统设计。Gunicorn主进程(Master)负责管理多个工作进程(Worker),每个Worker处理实际请求。关键点在于,Gunicorn的日志记录不是直接让多个进程同时写同一个文件,而是通过主进程来集中处理。
具体来说,Gunicorn使用了Python的logging模块,并配置了进程安全的处理器。当Worker进程需要记录日志时,它们并不是直接写入文件,而是将日志消息发送给主进程。主进程有一个专门的日志处理器(比如logging.handlers.WatcherFileHandler或类似的机制),它在一个单独的线程或进程中接收这些消息,并按顺序写入文件。这就避免了多个进程同时写文件可能导致的日志行交错或数据损坏。
此外,Gunicorn还支持通过--log-syslog等选项将日志发送到系统日志服务(如syslog),这些服务本身是设计用来处理并发写入的。
所以,简单讲,Gunicorn通过主进程集中记录日志,避免了多进程直接竞争文件资源,从而保证了日志的整洁有序。
总结:主进程统一写日志,自然不乱。
Linux 有个特性,你使用 APPEND 方式打开文件句柄,每次写入的量小于 PIPE_BUF_MAX ,那么系统能保证多进程之间不冲突
因为 linux 控制台保证了输出的进程安全
作者没有遇到多个日志文件切分时 有的 worker 进程还往老的文件里写的问题吗


