Laravel 9中如何为report()添加异常上下文日志?
解决方法
下面给你几种在Laravel中给异常日志添加上下文数据的实用方案:
1. 自定义带上下文的异常类
创建一个支持上下文存储的自定义异常,把需要的变量数据封装进去,再传递给report():
// 先定义自定义异常类 class CustomerPointsException extends \Exception { protected $context; public function __construct(string $message, array $context = [], int $code = 0, ?Throwable $previous = null) { $this->context = $context; parent::__construct($message, $code, $previous); } public function getContext(): array { return $this->context; } } // 业务代码里的try-catch try { $customerPointsService->subtractPointsForRewardReservation($customerReward); } catch(\Throwable $e) { // 把需要的变量打包成上下文,传入自定义异常 $context = [ 'customer_reward_id' => $customerReward->id ?? null, 'current_points' => $customerReward->customer->points ?? null, // 其他你需要的变量 ]; report(new CustomerPointsException($e->getMessage(), $context, $e->getCode(), $e)); return $this->sendJsonErrorWithCorrectStatusCode("Customer point subtraction failed.", [], 422); }
然后在app/Exceptions/Handler.php的report方法里,读取这个上下文并添加到日志:
public function report(Throwable $exception) { if ($exception instanceof CustomerPointsException) { Log::error($exception->getMessage(), $exception->getContext()); return; // 或者继续调用parent::report($exception),根据需求选择 } parent::report($exception); }
2. 临时设置日志上下文
利用Laravel的Log::withContext()方法,在调用report()前临时注入上下文数据,这样异常日志会自动带上这些信息:
try { $customerPointsService->subtractPointsForRewardReservation($customerReward); } catch(\Throwable $e) { // 设置日志上下文 Log::withContext([ 'customer_reward' => $customerReward->toArray() ?? [], 'error_message' => $e->getMessage(), // 其他变量 ]); report($e); return $this->sendJsonErrorWithCorrectStatusCode("Customer point subtraction failed.", [], 422); }
这个方法不需要修改异常类,适合快速临时添加上下文,上下文会作用于当前请求周期内的所有日志。
3. 给异常动态添加上下文属性
如果不想创建自定义异常,可以直接给捕获到的异常动态添加属性,然后在异常处理器里读取:
try { $customerPointsService->subtractPointsForRewardReservation($customerReward); } catch(\Throwable $e) { // 动态添加上下文属性 $e->context = [ 'customer_reward_id' => $customerReward->id, 'points_to_subtract' => $customerReward->points_required, ]; report($e); return $this->sendJsonErrorWithCorrectStatusCode("Customer point subtraction failed.", [], 422); }
然后在Handler.php的report方法中处理:
public function report(Throwable $exception) { if (property_exists($exception, 'context')) { Log::error($exception, $exception->context); } parent::report($exception); }
内容的提问来源于stack exchange,提问作者Čamo
相关产品推荐
相关产品推荐

