在静态上下文中使用 log4php
我目前正在从我们自己的专有日志记录解决方案迁移到 log4php。
我们在项目中使用了很多仅包含静态方法的类。该文档定义了基本用例,例如:
class MyClass {
private $logger;
public function __construct() {
$this->logger = Logger::getLogger(__CLASS__);
$this->logger->debug('currently in constructor');
}
}
但我不能使用它,因为我也需要 $logger
在静态上下文中可用。将 $logger
设为静态也没有帮助,因为我的类的构造函数永远不会被调用(因为它的所有成员都是静态的)。
文档告诉我为该成员使用静态初始值设定项。但随后我必须记住为我使用的所有类调用它。这似乎太容易出错了。
所以我想出了这个:
class Foo {
private static $logger = null;
private static function logger() {
if( null == self::$logger ) self::$logger = Logger::getLogger( __CLASS__ );
return self::$logger;
}
public static function bar() {
self::logger()->debug( "test" );
}
}
Foo::bar();
但这似乎也太大了。那么,有什么建议吗?
I'm currently in the process of moving from our own proprietary logging solution to log4php.
We use a lot of classes with only static methods in our project. The documentation defines the basic use case like:
class MyClass {
private $logger;
public function __construct() {
$this->logger = Logger::getLogger(__CLASS__);
$this->logger->debug('currently in constructor');
}
}
But I can't use that, cause I need $logger
to be available in a static context as well. Making $logger
static as well doesn't help either, because the constructor for my class is never called (as all its members are static).
The documentation tells me to use a static initializer for that member then. But then I would have to remember to call that for all classes I use. And that seems too error-prone.
So I came up with this:
class Foo {
private static $logger = null;
private static function logger() {
if( null == self::$logger ) self::$logger = Logger::getLogger( __CLASS__ );
return self::$logger;
}
public static function bar() {
self::logger()->debug( "test" );
}
}
Foo::bar();
But that seems like too much overhead as well. So, any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想出了一种效果很好的解决方案,但需要
$logger
公开。我只需为每个类定义一次
$logger
属性,并运行一次初始化代码(我猜是在应用程序入口点的require_once
部分之后)。该代码对性能的影响可以忽略不计,特别是因为它只运行一次(与我最初的解决方案相比)。这是我在 Intel Core2 Q9450 @2.66GHz 上的 VirtualBox VM 中测量的结果:
I came up with one solution that works quite well but requires
$logger
to be public.This I only have to define the
$logger
property once per class and run my initialization code once (I guess after therequire_once
section of the entry point of my application).The performance impact of that code is negligible, especially since it is only run once (compared to my initial solution). This is what I measured inside a VirtualBox VM on an Intel Core2 Q9450 @2.66GHz: