---
title: Log All Relevant Context On Errors
impact: HIGH
impactDescription: enables rapid debugging and incident resolution
tags: error-handling, logging, context, debugging, quality, php
---

## Log All Relevant Context On Errors

When an error occurs, simply logging the message "An error occurred" is insufficient. Effective debugging requires structured logs that include the error cause and the state of the application at that moment.

**Incorrect (minimal context):**

```php
Log::error('Error occurred');
Log::error($e->getMessage()); // Missing stack trace and context
```

**Correct (structured logging with Monolog/Laravel Context):**

```php
try {
    $this->paymentService->process($order);
} catch (\Throwable $e) {
    Log::error('Order processing failed', [
        // The Exception itself (Monolog handles the stack trace)
        'exception' => $e,
        
        // Business Context
        'order_id' => $order->id,
        'user_id' => auth()->id(),
        'amount' => $order->amount,
        
        // Request Metadata
        'url' => request()->fullUrl(),
        'method' => request()->method(),
        'ip' => request()->ip(),
        
        // Performance/Timing
        'duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
    ]);
    
    throw $e; // Re-throw if necessary
}
```

**Essential Context to Include:**
1. **The Exception**: Pass the entire exception object to the logger so it can extract the message, file, line, and full stack trace.
2. **Entity Identifiers**: IDs of the users, orders, or products involved.
3. **Correlation IDs**: Use unique request IDs (e.g., from `X-Request-ID` header) to trace a single request across multiple logs.
4. **Input State**: A summary of the input that lead to the error (excluding sensitive data like passwords).
5. **Environment**: App environment (`production`, `staging`) and server name.

**Tools:** Monolog, Sentry, Laravel Logging, New Relic, ELK Stack
