日志使用堆栈跟踪捕获异常 [英] Log caught exception with stack trace
问题描述
如果我没有在PHP中捕获异常,我将在我的 error.log
文件中收到一个有用的错误消息。例如,如果我运行:
If I don't catch an exception in PHP, I get a helpful error message in my error.log
file with a stack trace. For example, if I run:
<?php
function foo() {
throw new Exception('Oh no!');
}
foo();
?>
然后我将其写到我的日志中:
then I get this written to my logs:
[Wed Mar 06 10:35:32 2013] [错误] [客户端86.146.145.175] PHP致命
错误:未捕获异常异常与消息哦不!在
/var/www/test.php:4\\\
Stack trace:\\\
#0 /var/www/test.php(7):
foo()\\\
#1 {主要} \\\
在第4行/var/www/test.php中抛出
[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
有时我想抓住异常但仍记录该细节。我想象的是:
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);
}
?>
其中 log_exception
将写入错误日志某些东西基本上与自动为一个未捕获的异常编写的格式相同 - 除了具有捕获异常
而不是 PHP致命错误:未捕获异常
。
where log_exception
will 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 exception
instead of PHP Fatal error: Uncaught exception
.
是否有内置函数来记录异常信息,或将其捕获到字符串?我想象在Python中的 traceback.format_exc()
的分析。
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.
推荐答案
error_log($e);
做你想要的它记录完全相同的事情,如果你没有捕获异常,减去开头的单词未捕获。这样做是因为这是 异常
class's __ toString()
magic method 返回。
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 Exception
class's __toString()
magic method returns.
你可以在 catch
block:
You can do this in a catch
block:
try {
foo();
} catch (Exception $e) {
error_log("Caught $e");
}
或在异常处理程序中:
set_exception_handler(function($exception) {
error_log($exception);
error_page("Something went wrong!");
});
这篇关于日志使用堆栈跟踪捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!