插件窝 干货文章 ThinkPHP中如何优雅打印详细异常日志像Laravel一样?

ThinkPHP中如何优雅打印详细异常日志像Laravel一样?

异常 think Exception 处理 577    来源:    2025-03-13

在ThinkPHP中,虽然默认的异常处理机制已经足够强大,但如果你希望像Laravel一样优雅地打印详细的异常日志,可以通过以下几种方式来实现:

1. 使用Log类手动记录异常

ThinkPHP提供了Log类来记录日志。你可以在捕获异常时,手动将异常信息记录到日志中。

try {
    // 你的业务逻辑代码
} catch (\Exception $e) {
    // 记录异常日志
    \think\facade\Log::error($e->getMessage(), [
        'file' => $e->getFile(),
        'line' => $e->getLine(),
        'trace' => $e->getTraceAsString(),
    ]);
}

2. 自定义异常处理类

你可以通过自定义异常处理类来捕获并记录异常信息。首先,创建一个自定义的异常处理类,然后在app/ExceptionHandle.php中使用它。

namespace app;

use think\exception\Handle;
use think\exception\ErrorException;
use think\exception\ValidateException;
use think\exception\HttpException;
use think\facade\Log;

class ExceptionHandle extends Handle
{
    public function render($request, \Throwable $e)
    {
        // 记录异常日志
        Log::error($e->getMessage(), [
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'trace' => $e->getTraceAsString(),
        ]);

        // 其他异常处理逻辑
        return parent::render($request, $e);
    }
}

3. 使用app_debug配置

在ThinkPHP中,app_debug配置项决定了是否显示详细的错误信息。你可以在config/app.php中设置app_debugtrue,这样在开发环境下,系统会自动显示详细的错误信息。

// config/app.php
return [
    'app_debug' => true,
    // 其他配置项
];

4. 使用think-trace扩展包

think-trace是一个ThinkPHP的扩展包,它可以像Laravel的Whoops一样,提供更加友好的错误页面和详细的错误信息。

首先,安装think-trace扩展包:

composer require topthink/think-trace

然后,在config/trace.php中配置:

return [
    'type' => 'html', // 支持 html, json, xml
    'trace_tabs' => [
        'base'  => '基本',
        'file'  => '文件',
        'info'  => '信息',
        'sql'   => 'SQL',
        'debug' => '调试',
        'error' => '错误',
    ],
];

5. 使用think-exception扩展包

think-exception是ThinkPHP官方提供的异常处理扩展包,它可以帮助你更好地处理异常。

首先,安装think-exception扩展包:

composer require topthink/think-exception

然后,在app/ExceptionHandle.php中使用它:

namespace app;

use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\facade\Log;
use think\exception\ErrorException;

class ExceptionHandle extends Handle
{
    public function render($request, \Throwable $e)
    {
        // 记录异常日志
        Log::error($e->getMessage(), [
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'trace' => $e->getTraceAsString(),
        ]);

        // 其他异常处理逻辑
        return parent::render($request, $e);
    }
}

总结

通过以上几种方式,你可以在ThinkPHP中实现类似Laravel的异常日志记录功能。根据你的需求选择合适的方式,或者结合多种方式来实现更强大的异常处理机制。