使用PHP从输入模式搜索日志文件


Searching a log file using PHP from input pattern

我的问题是创建一个可以在日志文件中搜索的搜索函数。

模式是这样的:

node-id > command
-Date-other descriptions
Output starts
Output ends
node-id > another command

现在,我遇到的问题是从一个日志文件中截取一个命令的输出,并将其与另一个日志的输出进行比较。我找不到搜索内容并将其存储到数组或文件中以进行进一步比较的方法。

您不能从文件中剪切内容,只能更改文件并重新保存(根据您的文件系统,您可能会直接剪切内容,但在这里问这个问题意味着您没有这种低级文件系统经验)

在php中,它可能类似于:

$data = file_get_contents($fileToCutFrom);
// ... modify data here, e.g. if it's xml you might wanna use SimpleXML or DOMDocument or some other xml parser, like ganon ( https://code.google.com/p/ganon/ ) - the later one is pretty good if you know you might have incomplete/invalid xml
file_put_contents($fileToCutFrom, $modifiedData);

// and now append to the other file
file_put_contents($fileToAppendTo, $dataToAppend, FILE_APPEND);

但是,要知道,如果从多个文件执行此操作,您可能会遇到严重的竞争情况,因为file_get_contents不是原子的,file_put_contents也不是原子的。然后,您还会遇到要执行多行的问题。因此,如果您的代码可能同时执行多次,您可能希望使用一个脚本实例来执行所有的"剪切"和附加操作,打开一个套接字,而其他脚本只需将所需内容发送到该文件。

此外,如果你想在新数据进入时继续这样做,你可能想看看inotify(linux)或你系统上的同类产品(osx也有文件通知服务,但我不知道windows)

如果你需要一些不同的东西,你可能想在你的问题中添加信息。