# Enhanced Logging with Source Context

This document explains the enhanced logging system that captures source context information (class name, method name, file path, line number) for logs stored in the database.

## Overview

The enhanced logging system adds source context information to log records, making it easier to identify where errors and warnings are coming from in the codebase. This is particularly useful for debugging and troubleshooting issues in production environments.

## How It Works

1. A custom processor (`SourceContextProcessor`) has been added to the database logger.
2. This processor captures the source context information (class name, method name, file path, line number) from the call stack.
3. The source context information is added to the log record's context under a 'source' key.
4. The context is stored as JSON in the database.

## Viewing Logs with Source Information

### Admin Panel

The existing logs page in the admin panel has been enhanced to display source information for each log entry. When viewing log details, you'll now see the source information (class, method, file, line) if available.

### API Endpoints

For testing and development purposes, the following API endpoints are available:

- `GET /log-example/generate` - Generates example logs with source context
- `GET /log-example/view` - Views logs with source information
- `GET /log-example/sources` - Views a summary of error sources

## Using the Enhanced Logging System

### Basic Logging

You can use the standard Laravel logging methods as usual:

```php
use Illuminate\Support\Facades\Log;

Log::debug('This is a debug message');
Log::info('This is an info message');
Log::notice('This is a notice message');
Log::warning('This is a warning message');
Log::error('This is an error message');
Log::critical('This is a critical message');
Log::alert('This is an alert message');
Log::emergency('This is an emergency message');
```

The source context information will be automatically captured and stored with the log.

### Logging with Additional Context

You can also add additional context to your logs:

```php
Log::error('An error occurred', [
    'user_id' => $user->id,
    'action' => 'update_profile',
    'data' => $request->all()
]);
```

The source context information will be added to this context automatically.

### Logging Exceptions

When logging exceptions, it's recommended to include the exception in the context:

```php
try {
    // Some code that might throw an exception
} catch (\Exception $e) {
    Log::error('An error occurred: ' . $e->getMessage(), [
        'exception' => $e,
        'user_id' => $user->id ?? null
    ]);
}
```

## Helper Methods

The `LogHelper` class provides methods for retrieving logs with source information:

### Get Logs with Source Information

```php
use App\Helpers\LogHelper;

// Get all logs with source information
$logs = LogHelper::getLogsWithSource();

// Get error logs with source information
$errorLogs = LogHelper::getLogsWithSource('error');

// Get logs with source information, limited to 50 records
$limitedLogs = LogHelper::getLogsWithSource(null, 50);

// Get logs with source information, filtered by search term
$searchLogs = LogHelper::getLogsWithSource(null, 100, 'UserController');
```

### Get Error Sources Summary

```php
use App\Helpers\LogHelper;

// Get a summary of error sources
$errorSources = LogHelper::getErrorSourcesSummary();

// Get a summary of warning sources
$warningSources = LogHelper::getErrorSourcesSummary('warning');

// Get top 20 error sources
$topErrorSources = LogHelper::getErrorSourcesSummary('error', 20);
```

## Example Usage

Here's an example of how to use the enhanced logging system in a controller:

```php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Models\User;

class UserController extends Controller
{
    public function update(Request $request, $id)
    {
        try {
            $user = User::findOrFail($id);
            
            // Log the update attempt
            Log::info('Updating user profile', [
                'user_id' => $id,
                'data' => $request->except('password')
            ]);
            
            $user->update($request->validated());
            
            return response()->json(['message' => 'User updated successfully']);
        } catch (\Exception $e) {
            // Log the error with context
            Log::error('Failed to update user: ' . $e->getMessage(), [
                'exception' => $e,
                'user_id' => $id,
                'data' => $request->except('password')
            ]);
            
            return response()->json(['error' => 'Failed to update user'], 500);
        }
    }
}
```

In this example, if an error occurs, the log will include:
- The error message
- The exception details
- The user ID and request data
- The source context information (UserController class, update method, file path, line number)

This makes it much easier to identify and fix the issue.

## Conclusion

The enhanced logging system provides valuable context for debugging and troubleshooting issues in your application. By automatically capturing the source of each log entry, you can quickly identify where errors and warnings are coming from and fix them more efficiently.
