【问题标题】:How to output exception information in log file with log4php?如何使用 log4php 在日志文件中输出异常信息?
【发布时间】:2011-10-29 18:16:54
【问题描述】:
【问题讨论】:
标签:
php
exception
logging
log4php
【解决方案1】:
我花了一段时间才弄清楚为什么在抛出异常时 log4php 没有记录原始文件名和行号。事实证明,我的自定义 exception_handler 类仅记录异常消息(通过执行 $exception->getMessage()),其中不包含文件名和行号。我要做的就是连接这些信息:$exception->getFile() 和 $exception->getLine():
public function exception_handler ($exception) {
$logger = Logger9::create();
$logger->info($exception->getMessage()." ".$exception->getFile()." ".$exception->getLine());
}
不要忘记注册自定义处理程序:
@set_exception_handler(array($this, 'exception_handler'));
【解决方案3】:
我得出了同样的结论:看起来 log4php 只对 LoggerAppenderMongoDB.php 附加程序中的 $throwable 参数做了一些事情。
LoggerAppenderFile 基类依赖于布局 LoggerLayoutTTCC 来格式化消息(正如预期的那样)。该类有一个方法ignoresThrowable(),它返回true。虽然这个方法似乎没有被调用,但它确实温和地表明作者似乎并不打算注意这个错误。
我添加了自己的布局类,它扩展了 LoggerLayoutTTCC 并覆盖了 format()
class LoggerLayoutTTCCWithException extends LoggerLayoutTTCC
{
public function format(LoggerLoggingEvent $event) {
$format = parent::format($event);
$throwableInfo = $event->getThrowableInformation();
if ($throwableInfo === null) {
return $format;
}
$renderer = new LoggerRendererException();
return $format . $renderer->render($throwableInfo->getThrowable());
}
}