php 使用堆栈跟踪记录捕获的异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15245184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:53:06  来源:igfitidea点击:

Log caught exception with stack trace

phpexceptionlogging

提问by Mark Amery

If I don't catch an exception in PHP, I get a helpful error message in my error.logfile with a stack trace. For example, if I run:

如果我没有在 PHP 中捕获异常,我会在我的error.log文件中收到一条带有堆栈跟踪的有用错误消息。例如,如果我运行:

<?php

  function foo() {
    throw new Exception('Oh no!');
  } 

  foo();

?>

then I get this written to my logs:

然后我把它写到我的日志中:

[Wed Mar 06 10:35:32 2013] [error] [client 86.146.145.175] PHP Fatal error: Uncaught exception 'Exception' with message 'Oh no!' in /var/www/test.php:4\nStack trace:\n#0 /var/www/test.php(7): foo()\n#1 {main}\n thrown in /var/www/test.php on line 4

[2013 年 3 月 6 日星期三 10:35:32] [错误] [客户端 86.146.145.175] PHP 致命错误:未捕获的异常“异常”,消息为“哦,不!” 在 /var/www/test.php:4\n堆栈跟踪:\n#0 /var/www/test.php(7): foo()\n#1 {main}\n 抛出在 /var/www/第 4 行的 test.php

Sometimes I'd like to catch the exception but still log that detail. I'm imagining something like:

有时我想捕获异常但仍记录该详细信息。我在想象这样的事情:

<?php

  function foo() {
    throw new Exception('Oh no!');
  } 

  try {
      foo();
  } catch (Exception $e) {
      log_exception($e);
  }

?>

where log_exceptionwill write to the error log something in basically the same format as what gets automatically written for an uncaught exception - perhaps literally identical besides having Caught exceptioninstead of PHP Fatal error: Uncaught exception.

wherelog_exception将以与为未捕获的异常自动写入的格式基本相同的格式写入错误日志 - 除了具有Caught exception而不是PHP Fatal error: Uncaught exception.

Is there a built-in function to log exception info like this, or to capture it to a string? I'm imagining something analagous to traceback.format_exc()in Python.

是否有内置函数来记录这样的异常信息,或者将其捕获为字符串?我正在想象一些类似于traceback.format_exc()Python 的东西。

回答by Jay K

error_log($e);

does what you want. It logs exactly the same thing that would have been logged if you didn't catch the exception, minus the word 'Uncaught' at the beginning. It does this because that's what the Exceptionclass's __toString()magic methodreturns.

做你想做的。如果您没有捕获异常,它会记录完全相同的内容,减去开头的“未捕获”一词。这样做是因为这就是Exception类的__toString()魔法方法返回的内容。

You can do this in a catchblock:

您可以在catch块中执行此操作:

try {
    foo();
} catch (Exception $e) {
    error_log("Caught $e");
}

Or in the exception handler:

或者在异常处理程序中:

set_exception_handler(function($exception) {
    error_log($exception);
    error_page("Something went wrong!");
});

回答by enricog

You can use the methods from PHP's base Exceptionclass.

您可以使用PHP 基Exception类中的方法。

Use getMessageto get the message Oh no!and use getTraceAsStringto get a formatted trace.

使用getMessage得到的消息Oh no!和使用getTraceAsString得到一个格式化的跟踪。

回答by Eelke van den Bos

We use Monolog to do the logging in our application. Monolog has a formatter that can print stack traces. To log exceptions with traces, we use a LineFormatter and call includeStacktraces() on it. (code below)

我们使用 Monolog 在我们的应用程序中进行日志记录。Monolog 有一个可以打印堆栈跟踪的格式化程序。要使用跟踪记录异常,我们使用 LineFormatter 并在其上调用 includeStacktraces()。(代码如下)

$handler = new \Monolog\Handler\StreamHandler(STDOUT);

$lineFormatter = new \Monolog\Formatter\LineFormatter();
$lineFormatter->includeStacktraces();

$handler->setFormatter($lineFormatter);

$logger = new \Monolog\Logger('root', [$handler]);

try {
    //do some throwing
} catch (Exception $e) {
    //do some logging, add exception to context
    $logger->error($e->getMessage(), ['exception' => $e]);
}

回答by varuog

You can use http://php.net/manual/en/function.set-exception-handler.phpto register a callback function which would get the message from $e->getMessage(); and dump it to file.

您可以使用http://php.net/manual/en/function.set-exception-handler.php注册一个回调函数,该函数将从 $e->getMessage() 获取消息;并将其转储到文件中。