gpt4 book ai didi

python - python日志记录是否支持多处理?

转载 作者:IT老高 更新时间:2023-10-28 20:32:44 25 4
gpt4 key购买 nike

有人告诉我,日志记录不能在多处理中使用。你必须做并发控制,以防多处理弄乱日志。

但我做了一些测试,在多处理中使用登录似乎没有问题

import time
import logging
from multiprocessing import Process, current_process, pool


# setup log
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='/tmp/test.log',
filemode='w')


def func(the_time, logger):
proc = current_process()
while True:
if time.time() >= the_time:
logger.info('proc name %s id %s' % (proc.name, proc.pid))
return



if __name__ == '__main__':

the_time = time.time() + 5

for x in xrange(1, 10):
proc = Process(target=func, name=x, args=(the_time, logger))
proc.start()

从代码中可以看出。

我故意让子进程在同一时刻(启动后5s)写入日志,以增加冲突的机会。但是完全没有冲突。

所以我的问题是我们可以在多处理中使用日志记录吗?为什么这么多帖子说我们不能?

最佳答案

正如 Matino 正确解释的那样:登录多进程设置并不安全,因为多个进程(它们对现有的其他进程一无所知)正在写入同一个文件,可能会相互干扰。

现在发生的情况是每个进程都持有一个打开的文件句柄,并对该文件进行“追加写入”。问题是在什么情况下追加写入是“原子的”(也就是说,不能被例如另一个进程写入同一个文件并混合他的输出而中断)。这个问题适用于每一种编程语言,因为最终它们会对内核进行系统调用。 This answer回答在什么情况下共享日志文件是可以的。

它归结为检查您的管道缓冲区大小,在 /usr/include/linux/limits.h 中定义的 linux 上是 4096 字节。对于其他操作系统,您可以找到 here一个很好的 list 。

这意味着:如果您的日志行小于 4'096 字节(如果在 Linux 上),那么附加是安全的,如果磁盘是直接连接的(即中间没有网络)。但有关更多详细信息,请查看我的答案中的第一个链接。要对此进行测试,您可以使用不同的 logger.info('proc name %s id %s %s' % (proc.name, proc.pid, str(proc.name)*5000))长度。以 5000 为例,我已经在 /tmp/test.log 中混淆了日志行。

this question已经有不少解决方案了,这里就不添加自己的解决方案了。

更新:Flask 和多处理

Web frameworks like flask will be run in multiple workers if hosted by uwsgi or nginx. In that case, multiple processes may write into one log file. Will it have problems?

flask 中的错误处理是通过 stdout/stderr 完成的,然后由 web 服务器(uwsgi、nginx 等)处理,需要注意日志以正确的方式写入(参见例如 [this flask+nginx example ])( http://flaviusim.com/blog/Deploying-Flask-with-nginx-uWSGI-and-Supervisor/ ),可能还会添加进程信息,以便您可以将错误行与进程相关联。来自 flasks doc :

By default as of Flask 0.11, errors are logged to your webserver’s log automatically. Warnings however are not.

因此,如果您使用 warn 并且消息超出管道缓冲区大小,您仍然会遇到混合日志文件的问题。

关于python - python日志记录是否支持多处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47968861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com