首页 > 解决方案 > Python 原子日志

问题描述

我有一个在几千个进程上运行的记录器,它们都以附加模式写入同一个文件。什么是保证写入是原子性的好方法——也就是说,每次进程写入日志时,它的全部内容都写入一个块中,并且没有其他进程同时写入该文件?

我的想法是做类似的事情:

logger          = getLogger()
global_lockfile = '/tmp/loglock'

def atomic_log(msg):
    while True:
        if os.path.exists(lockfile):
            continue
        with open(lockfile, 'w') as f:
            logger.write(msg)
        os.remove(lockfile)
    

def some_function(request):
    log_atomic("Hello")

在 posix 系统上执行上述操作的实际方法是什么?

标签: python

解决方案


推荐阅读