我使用Monolog 1.25.1和PHP 7.1来登录我的本地环境,并使用Monolog的SyslogHandler将记录写入日志流。
为了检查文字在竞争条件下的表现,我创建了一个简单的python脚本,该脚本生成20个线程,这些线程同时命中了我的api端点之一:
import requests
from concurrent.futures import ThreadPoolExecutor
from requests.auth import HTTPBasicAuth
def get_url(url):
return requests.get(url)
with ThreadPoolExecutor(max_workers=20) as pool:
print(list(pool.map(get_url,["my/api/endpoint"]*20)))
在端点中的某处触发了日志处理程序,并在日志中写入一条记录。
我还应该提到,该文件已设置为通过rsyslog.conf配置异步写入记录。
我的问题是,并非所有日志记录都一次写入日志文件中。在20条记录中,日志文件包含以下记录:
timestamp1;my/api/endpoint;custom_message
message repeated 10 times: [timestamp1;my/api/endpoing;custom_message]
timestamp2;my/api/endpoint;custom_message
因此该文件包含20条记录中的12条记录。现在,下次我写入日志文件时,在新记录出现之前,其他8条记录将附加在文件末尾:
timestamp1;my/api/endpoint;custom_message
message repeated 10 times: [timestamp1;my/api/endpoing;custom_message]
timestamp2;my/api/endpoint;custom_message
message repeated 8 times: [timestamp2;my/api/endpoing;custom_message]
此行为是否有任何解释?我猜想这与rsyslog在写入所有记录之前锁定文件有关,然后缓冲这些记录并在重新打开文件后将它们写入。