【问题标题】:How to output exception information in log file with log4php?如何使用 log4php 在日志文件中输出异常信息?
【发布时间】:2011-10-29 18:16:54
【问题描述】:

我已经设置log4php 使用LoggerAppenderRollingFile appender 和LoggerLayoutTTCC 布局记录到文件。但是,当我记录异常时,它不会像我在 log4net 中看到的那样显示异常详细信息,例如堆栈跟踪。

我快速浏览了代码,看起来LoggerAppenderMongoDB 支持使用formatThrowable method 显示异常,但我在其他附加程序中看不到任何类似的东西。

我觉得我错过了一些明显的东西。是否需要配置一些东西才能将这些详细信息打印到日志文件中?我需要创建一个自定义 LoggerAppender 类吗?或者这些可以通过不同的布局或自定义渲染器来完成吗?

【问题讨论】:

    标签: 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'));
    

    【讨论】:

      【解决方案2】:

      仅供参考,现在 LoggerLayoutTTCC 已被弃用,您可以使用带有更好格式字符串的 LoggerLayoutPattern 来包含异常。

      <layout class="LoggerLayoutPattern">
         <param name="conversionPattern" value="%d{m/d/y H:i:s,u} [%t] %p %c %x - %m %newline%throwable" />
      </layout>
      
      <!-- %newline%throwable is the important part -->
      

      请参阅文档的日志记录异常部分:http://logging.apache.org/log4php/docs/layouts/pattern.html#Logging_exceptions

      【讨论】:

        【解决方案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());
                }
            }
        

        【讨论】:

          【解决方案4】:

          您应该使用 PHP set_exception_handler 函数并使用该函数包装 log4php。 查看:http://php.net/manual/en/function.set-exception-handler.php

          function exception_handler($exception) {
          

          $log->debug($exception->getMessage()); }

          set_exception_handler('exception_handler');

          【讨论】:

            猜你喜欢
            • 2016-01-21
            • 1970-01-01
            • 1970-01-01
            • 2019-05-25
            • 1970-01-01
            • 2018-09-02
            • 2020-01-06
            • 2018-03-13
            • 1970-01-01
            相关资源
            最近更新 更多