0
点赞
收藏
分享

微信扫一扫

PHP错误日志跟踪记录register_shutdown_function/set_error_handler/set_exception_handler


写程序不可避免有错误,而调试错误就很重要了,需要看错误信息,错误发生的文件、行号等,特别是对于线上的系统调试,不能让用户看到错误信息,这就需要把错误信息记录日志里。除了使用​​try catch​​​,还可以使用​​set_error_handler​​。

// 定义PHP程序执行完成后执行的函数
register_shutdown_function(['Debug', 'fatalError']);

// 设置一个用户定义的错误处理函数
set_error_handler(["Debug", "appError"]);

//自定义异常处理。
set_exception_handler(['Debug', 'appException']);

下面简单写了一段错误记录的小程序。

<?php
function myErrorHandler($errno, $errstr, $errfile, $errline){
$f = fopen("log.txt", "a");
fwrite($f, $errno."\n".$errstr."\n".$errfile."\n".$errline."\n");
fwrite($f, var_export(debug_backtrace(), true));
fclose($f);
// error_log($errstr);
// 返回true 在前端不报错,返回false就会在前端报错
return true;
}

// 设置错误处理函数
set_error_handler("myErrorHandler", E_ALL);

// 测试
function fe() {
$a = 1/0;
for($i=0;$i<10;$i++) {
echo($i."<br/>");
}
return 0;
}
fe();

参考:
​​​http://php.net/manual/zh/book.errorfunc.php​​​​​​

​​http://php.net/manual/zh/ref.funchand.php​​


举报

相关推荐

0 条评论