插件窝 干货文章 ThinkPHP如何优雅打印包含详细堆栈信息的错误日志?

ThinkPHP如何优雅打印包含详细堆栈信息的错误日志?

堆栈 信息 Exception 错误 221    来源:    2025-03-13

在ThinkPHP中,优雅地打印包含详细堆栈信息的错误日志可以通过以下几种方式实现:

1. 使用 Log 类记录错误日志

ThinkPHP 提供了 Log 类来记录日志。你可以使用 Log::error() 方法来记录错误日志,并且可以通过 debug_backtrace() 函数获取详细的堆栈信息。

use think\facade\Log;

try {
    // 你的业务逻辑代码
} catch (\Exception $e) {
    // 记录错误日志
    Log::error('错误信息: ' . $e->getMessage());

    // 获取堆栈信息
    $trace = debug_backtrace();
    Log::error('堆栈信息: ' . print_r($trace, true));
}

2. 使用 Exception 类的 getTraceAsString 方法

Exception 类提供了 getTraceAsString() 方法,可以直接获取异常的堆栈信息字符串。

use think\facade\Log;

try {
    // 你的业务逻辑代码
} catch (\Exception $e) {
    // 记录错误日志
    Log::error('错误信息: ' . $e->getMessage());

    // 获取堆栈信息
    Log::error('堆栈信息: ' . $e->getTraceAsString());
}

3. 使用 Log 类的 write 方法

如果你需要更灵活地控制日志的格式和内容,可以使用 Log::write() 方法。

use think\facade\Log;

try {
    // 你的业务逻辑代码
} catch (\Exception $e) {
    // 记录错误日志
    $logContent = [
        '错误信息' => $e->getMessage(),
        '堆栈信息' => $e->getTraceAsString(),
    ];

    Log::write(json_encode($logContent, JSON_PRETTY_PRINT), 'error');
}

4. 配置日志格式

你可以在 config/log.php 中配置日志的格式,使其包含更多的信息,如时间、请求信息等。

return [
    'default'      => 'file',
    'channels'     => [
        'file' => [
            'type'  => 'file',
            'path'  => '',
            'level' => ['error'],
            'apart_level' => ['error'],
            'format' => '[%s][%s] %s', // 自定义日志格式
        ],
    ],
];

5. 使用 trace 函数

ThinkPHP 还提供了 trace 函数,可以在调试模式下输出调试信息。

try {
    // 你的业务逻辑代码
} catch (\Exception $e) {
    // 记录错误日志
    trace('错误信息: ' . $e->getMessage(), 'error');

    // 获取堆栈信息
    trace('堆栈信息: ' . $e->getTraceAsString(), 'error');
}

6. 使用 think\exception\Handle

如果你希望在全局捕获异常并记录日志,可以自定义异常处理类。

namespace app\exception;

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());
        Log::error('堆栈信息: ' . $e->getTraceAsString());

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

然后在 config/app.php 中配置自定义的异常处理类:

return [
    'exception_handle'       => 'app\exception\ExceptionHandle',
];

总结

通过以上几种方式,你可以在ThinkPHP中优雅地打印包含详细堆栈信息的错误日志。根据你的需求选择合适的方式,确保在开发和生产环境中能够有效地捕获和记录错误信息。