2

我在 apache2 上有一个 WSGI 应用程序,它以最简单的方式写入日志文件:

def log (msg):
    with open (LOGFILE, 'a') as f: f.write (msg)

在我的沙盒环境中它运行良好,不过我有点担心并发性。如果 apache2 运行各种线程,我是否必须担心并发问题?也许我的日志文件会被打乱?log (msg)如果另一个线程已经在记录,是否会调用失败?如果是这种情况,我将如何防止它?

编辑: 为了测试,我从两个 shell 同时运行两个脚本:

#! /usr/bin/python3.2

def log ():
    with open ('log', 'a') as f:
        f.write ('message from thread A\n')

while (True): log ()

#! /usr/bin/python3.2

def log ():
    with open ('log', 'a') as f:
        f.write ('message from thread B\n')

while (True): log ()

日志文件看起来不错,没有发生错误。我是幸运的还是从两个不同的线程写入同一个文件是否安全。文件系统是 ext4。

4

2 回答 2

4

您可以使用 python日志记录模块

于 2012-12-16T01:05:07.957 回答
0

在 linux OS 中,确保使用 append 模式写入文件是原子的,因此不会发生错误

于 2013-10-09T11:49:19.177 回答