我通常使用Monolog进行PHP日志记录和调试,但是发现我最终将每个类实例化为自己的Monolog \ Logger,这对于其中只有一个或两个类的项目是很好的,但是我想使用Composer等在多个项目中共享这些类。为了避免让每个类使用其自己的记录器,我目前使用以下代码,该代码仅允许我传递Logger的实例(如果已配置),如果未配置,则该类将自行设置Null记录器:
/**
* Basic Constructor
*
* @param Logger|Null Logging instance or Null to do no logging at all
*/
public function __construct($logger = null)
{
if ($logger !== null) {
$this->logger = $logger;
} else {
$this->logger = new Logger('dummy');
$this->logger->pushHandler(new NullHandler());
}
}
private function test($var1,$var2) {
$this->logger->debug('test method called with '.$var1.' and '.$var2);
}
这是为我的类配置调试的最佳方法,还是更通用/更简单的编码实践?
过去我在类中也使用了一种方法来测试$ this-> debug是否不为null,如果是,则使用数据调用Logger,而不是将所有内容都发送给null Logger,但这需要使用多个方法每个日志级别:
/**
* If debug enabled, send all passed parameters to debugger
*/
public function debug()
{
if (is_null($this->debug)) {
return;
}
$args = func_get_args();
$this->debug->debug(print_r($args, true));
}
我没有使用任何预先构建的框架,但是当我将自己的类与框架一起使用时,我会认为仍然会出现相同的问题。
在全局名称空间中使用一个帮助器类,该类具有一些静态函数可访问。
class Debug {
static $logger = new Logger();
public static function debug($input) {
self::$logger->debug($input);
}
... for other functions/wrapping you wish to do
}
添加一些帮助功能
function debug($input)) {
Debug::debug($input);
}
然后您就可以出发了。
然后您可以进行debug('mystuff')或Debug :: debug('mystuff');
通过使用通过__callStatic接口的静态包装器类,您可以将您在记录器上执行的所有实例查询作为对调试类的静态调用传递,而不必担心将记录器的所有方法“复制”到您自己的Debug中包装纸。当您添加甚至一些帮助程序功能时,您不必为调试帮助程序键入太多内容
完整的基本示例:https://ideone.com/tAKBWr
<?php
class Logger {
public function debug($input) {
var_dump($input);
}
public function log($input) {
echo $input;
}
}
class Debug {
protected $logger;
protected static $_instance = NULL;
final private function __construct() {
$this->logger = new Logger();
}
final private function __clone() { }
final public static function getInstance()
{
if(null !== static::$_instance){
return static::$_instance;
}
static::$_instance = new static();
return static::$_instance;
}
public function getLogger()
{
return $this->logger;
}
static public function __callStatic($name, $args)
{
$logger = self::getInstance()->getLogger();
if(method_exists($logger, $name)) {
return $logger->{$name}(...$args);
}
}
}
function debug($input)
{
Debug::debug($input);
}
function traceLog($input)
{
Debug::log($input);
}
debug(['42','asdfasdf',33]);
traceLog("Moving to track 3");