日志使用堆栈跟踪捕获异常

编程入门 行业动态 更新时间:2024-10-28 12:29:41
本文介绍了日志使用堆栈跟踪捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我没有在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!"); });

更多推荐

日志使用堆栈跟踪捕获异常

本文发布于:2023-08-07 20:39:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1321653.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:堆栈   异常   日志

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!