lfbn / logger-trait
一个特性,允许您为任何类添加日志记录功能。
0.0.1
2020-01-09 16:01 UTC
Requires
- monolog/monolog: ^2.0
- psr/log: ^1.1
Requires (Dev)
- phpunit/phpunit: ^8.5
- roave/security-advisories: dev-master
This package is not auto-updated.
Last update: 2024-09-30 22:22:03 UTC
README
这是一个特性,允许在任何类中实现日志记录功能。
默认情况下,它使用Monolog并将流输出到标准输出,但您可以覆盖此行为。
安装
composer require lfbn/logger-trait
使用方法
使用默认行为
// In the class you want, add the use of the Trait. use LoggerTrait; (...) // After that, you can use it. $this->logError('Some message...', ['some context']);
更改名称、流或最小级别
// Implement the following protected properties. /* @var string */ protected static $loggerName = 'my-logger-name'; /* @var string */ protected static $loggerStream = 'php://stdout'; /* @var string */ protected static $loggerMinimumLevel = LogLevel::DEBUG;
覆盖默认行为
class MyClass { protected function initLogger(): bool { $this->logger = new \Monolog\Logger('Overriding default logger: '.$this->getLoggerName()); try { $handler = new StreamHandler( $this->getLoggerStream(), $this->getLoggerMinimumLevel() ); $this->logger->pushHandler($handler); } catch (Exception $e) { $this->logger = new NullLogger(); return false; } return true; } }
注入自己的记录器
class Test { use \Lfbn\LoggerTrait\LoggerTrait; public function test(): void { $this->logDebug('Hello TEST!'); } } $logger = new \Monolog\Logger('test4-my-own-logger'); try { $handler = new StreamHandler( 'php://stdout', 'debug' ); $logger->pushHandler($handler); } catch (Exception $e) { $logger = new NullLogger(); } $myClass = (new Test()); $myClass->setLogger($logger); $myClass->test();
插值消息
$this->logWarning( self::interpolateMessage( 'Hello my {private} TEST5!', ['private' => 'message'] ), );