aternos / codex
PHP 库,用于读取、解析、打印和分析日志文件。
Requires
- php: >=8.1
Requires (Dev)
- phpunit/phpunit: ^10.5
README
关于
Codex (拉丁语中约意为“日志”)是一个PHP库,用于读取、解析、打印和分析日志文件以查找问题和提出可能的解决方案。它主要针对Minecraft服务器日志,但也适用于其他类型的日志。这个库提供了一种结构化日志解析的实现方案,并提供了基于正则表达式的一些有用的基本实现。这个库的每个部分都可以或必须扩展/覆盖,同时仍需遵循接口,确保库的不同部分之间具有互操作性。
安装
composer require aternos/codex
用法
这是对Codex概念的简要介绍,更多示例请查看 测试 文件夹,或阅读 代码。
日志文件
要开始读取日志,需要实现 LogFile
接口的 LogFileInterface
对象。当前库中有三种不同的日志文件类。
<?php $logFile = new \Aternos\Codex\Log\File\StringLogFile("This is the log content"); $logFile = new \Aternos\Codex\Log\File\PathLogFile("/path/to/log"); $logFile = new \Aternos\Codex\Log\File\StreamLogFile(fopen("/path/to/log", "r"));
日志
Log
对象实现 LogInterface
是不同操作中最重要的对象。它代表日志内容,该内容被分割成 条目 和 行。它提供快速访问检测、解析和分析功能,并可以定义用于这些功能的类。如果您知道日志类型或只想测试默认的 Log 类,您可以直接创建一个新的实例,否则您可以使用以下描述的检测。
<?php $log = new \Aternos\Codex\Log\Log(); $log->setLogFile($logFile);
检测
如果日志类型(特别是日志类型的类名)未知,您可以使用 Detective
类来自动检测日志类型。该 Detective
类获取可能的日志类名列表,并执行它们的给定 检测器。
<?php $detective = new \Aternos\Codex\Detective\Detective(); $detective->addPossibleLogClass(\Aternos\Codex\Log\Log::class); $log = $detective->detect();
detect()
函数始终返回一个日志对象,如果需要,则默认为 Log
。
解析
解析器读取整个日志并创建Entry
和Line
对象,这些对象是Log
对象的一部分。不同的日志类型可以通过重写LogInterface::getDefaultParser()
函数或通过将解析器对象传递给解析函数来使用不同的解析器。
<?php $log->parse();
分析
通过一个Analyser
在AnalysableLog
上执行分析,并返回一个包含各种Insight
对象的Analysis
对象,例如一个Problem
对象或一个Information
对象。不同的日志类型可以通过重写AnalysableLogInterface::getDefaultAnalyser()
函数或通过将分析器对象传递给分析函数来使用不同的分析器。
<?php $analysis = $log->analyse();
打印
可以通过一个Printer
打印整个Log
或仅打印一个Entry
。基本的DefaultPrinter
按行打印纯文本内容。ModifiableDefaultPrinter
允许Modification
,例如突出显示某些字符/单词。
<?php $printer = new \Aternos\Codex\Printer\DefaultPrinter(); $printer->setLog($log); $printer->print(); $printer = new \Aternos\Codex\Printer\DefaultPrinter(); $printer->setEntry($entry); $printer->print(); $printer = new \Aternos\Codex\Printer\ModifiableDefaultPrinter(); $printer->setLog($log); $modification = new \Aternos\Codex\Printer\PatternModification(); $modification->setPattern('/foo/'); $modification->setReplacement('bar'); $printer->addModification($modification); $printer->print();