PHP set_exception_handler 设置异常处理函数
If you're handling sensitive data and you don't want exceptions logging details such as variable contents when you throw them, you may find yourself frustratedly looking for the bits and pieces that make up a normal stack trace output, so you can retain its legibility but just alter a few things. In that case, this may help you:
<?php
function exceptionHandler($exception) {
// these are our templates
$traceline = "#%s %s(%s): %s(%s)";
$msg = "PHP Fatal error: Uncaught exception '%s' with message '%s' in %s:%s Stack trace: %s thrown in %s on line %s";
// alter your trace as you please, here
$trace = $exception->getTrace();
foreach ($trace as $key => $stackPoint) {
// I'm converting arguments to their type
// (prevents passwords from ever getting logged as anything other than 'string')
$trace[$key]['args'] = array_map('gettype', $trace[$key]['args']);
}
// build your tracelines
$result = array();
foreach ($trace as $key => $stackPoint) {
$result[] = sprintf(
$traceline,
$key,
$stackPoint['file'],
$stackPoint['line'],
$stackPoint['function'],
implode(', ', $stackPoint['args'])
);
}
// trace always ends with {main}
$result[] = '#' . ++$key . ' {main}';
// write tracelines into main template
$msg = sprintf(
$msg,
get_class($exception),
$exception->getMessage(),
$exception->getFile(),
$exception->getLine(),
implode(" ", $result),
$exception->getFile(),
$exception->getLine()
);
// log or echo as you please
error_log($msg);
}
?>
If you're not a fan of sprintf() or the duplicate $exception->getFile() and $exception->getLine() calls you can of course replace that as you like - consider this a mere compilation of the parts.
相关文章
- 【PHP代码审计】 那些年我们一起挖掘SQL注入 - 2.全局防护Bypass之UrlDecode
- php 枚举类代替hard code代码
- 在 Linux 命令行中使用和执行 PHP 代码(一)
- PHP Warning: Xdebug MUST be loaded as a Zend extension in Unknown on line 0
- Mac - 使用php环境
- 基于PHP和JS的AES相互加密解密方法详解
- PHP 找到字符串第一次出现的位置并替换
- 编译安装php时提示Cannot find MySQL header files的解决方法
- PHP数组实际占用内存大小的分析
- php面向对象高级-魔术方法与迭代器
- PHP Catchable fatal error: Argument 2 passed to IlluminateRoutingUrlGenerator::__construct()
- Eclipse集成PDT+XDebug调试PHP脚本 https://svn.jcxsoftware.com/node?page=5 [转]