m1lt0n / dialog
PHP 5.4+ 的日志库
0.5.0
2015-08-25 11:05 UTC
Requires
- php: >=5.4.0
Requires (Dev)
This package is not auto-updated.
Last update: 2024-09-18 10:46:07 UTC
README
PSR-3 兼容的日志记录器
Dialog 是一个简单且非常可扩展的 PSR-3 兼容日志记录器。它是模块化的,允许每个日志记录实例有多个日志处理器。这允许在文件中同时记录、在屏幕上显示、写入数据库等!
此外,其灵活的结构还允许处理器接受格式化程序,也可以按照您想要的任何方式格式化日志消息行。
最后,遵循 PSR-3 指南的“模板”引擎(即“这是 {数量}”)也可以更改(当然,使用自定义引擎创建的日志记录器不会是 PSR-3 兼容的)。
示例
<?php // Pick the Engine (i.e. template/placeholder matcher, usually the Psr3Engine // provided with the package will suffice) $engine = new \Dialog\Message\Psr3Engine(new \Dialog\Message\ExceptionStringFormatter()); // Get a new HandlerBag to add Handlers for the log messages // This allows us to have several handlers and upon triggering log or any // log-level specific method, all of the handlers will do their job independently // (e.g. one may write on the screen, another in a file etc) $handlerBag = new \Dialog\Log\HandlerBag(); // Instantiate the Logger (this one is provided and is quite generic, so you can // use it out of the box! $logger = new \Dialog\Log\Logger($engine, $handlerBag); // Formatters, well, format the log line (e.g. include date? have the log level etc) $formatter = new \Dialog\Formatter\Formatter( new \Dialog\Formatter\DateTimeBuilder(), new \DialogFormatter\TemplateEngine()); // Output is where the output/result it prepared and stored // (if there is a storage mechanism in place, e.g. files/databases) // Currently more than one outputs are supported (Screen, File etc) $output = new \Dialog\Output\ScreenOutput(); // We create a Handler instance and assign a formatter and output mechanism // as well as a log level threshold from which the logger will start handling $handler1 = new \Dialog\Log\Handler($formatter, $output); $handler1->setThreshold(\Dialog\Log\LogLevel::WARNING); // We add the Handler in the handler bag registered with the Logger and we're done $handlerBag->add('screen1', $handler1); //---------------- // this message will be displayed $logger->log(\Dialog\Log\LogLevel::WARNING, 'test'); // this one will not as the threshold condition is not met $logger->log(\Dialog\Log\LogLevel::INFO, 'test');
也许上面的内容看起来像是大量的模板代码,但如今,使用依赖注入容器可以完成许多实例化行,而且日志和处理器类也可以被继承以注入默认依赖项,或者(可能更好)可以创建封装上述模板代码的工厂。总之,我们只用了大约 8 行模板代码,就成功地解耦了日志组件,并获得了巨大的灵活性。