使用apache log4php并由我的类中的帮助器方法调用它:
class MyClass{
function log($msg, $level='info'){
$log = @Logger::getLogger("MyLogger");
$log->$level($msg);
}
}上面代码的问题是file: logger中的line列将始终为help方法报告行num。我可以使用php的debug_backtrace()获得调用助手方法的原始行号和文件:
$bt = debug_backtrace();
$caller = array_shift($bt);所以我的问题是,在我的helper方法中有没有一种方法来设置file:line列?我在想,我可能需要重写一个Logger::方法或别的什么?
发布于 2013-03-08 15:45:43
我的解决方案是对源代码的黑客攻击,这是应该避免的。@Sven给出了一个答案,它应该涵盖大多数场景,但对我来说,我的日志调用必须通过helper方法。
在LoggerLoggingEvent.php类文件中添加方法:
/**
* Set the event location info
* @param LoggerLocationInfo $locationInfo
*/
public function setLocationInformation(LoggerLocationInfo $locationInfo) {
$this->locationInfo = $locationInfo;
}然后在日志类方法中使用:
/**
* Log an INFO message
* @param string $msg The message to log
* @return none
*/
public function log($msg, $level='info'){
// Manually construct a logging event
$level = LoggerLevel::toLevel($level);
$logger = Logger::getLogger(__CLASS__);
$event = new LoggerLoggingEvent(__CLASS__, $logger, $level, $msg);
// Override the location info
$bt = debug_backtrace();
$caller = array_shift($bt);
$location = new LoggerLocationInfo($caller);
$event->setLocationInformation($location);
// Log it
$logger->logEvent($event);
}发布于 2013-03-06 10:10:20
解决方案不是使用您自己的日志函数,而是在您现在调用您自己的日志函数的地方使用记录器。
class MyClass {
public function __construct() {
$this->logger = Logger::getLogger("MyLogger");
}
public function anywhere() {
// $this->log("Foo"); // Don't do this,
$this->logger->info("Foo"); // do this.
}
}通用日志记录框架无法知道日志调用实际进行了多少层间接层,并从回溯中剥离这些层。您还失去了将异常传递给记录器的能力。
https://stackoverflow.com/questions/15219327
复制相似问题