Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Api Logs Laravel Package

codetech/laravel-api-logs

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require codetech/laravel-api-logs
    

    The package auto-registers its service provider, but verify it exists in config/app.php under providers.

  2. Run Migrations:

    php artisan vendor:publish --provider="CodeTech\ApiLogs\Providers\ApiLogServiceProvider" --tag=migrations
    php artisan migrate
    

    This creates the api_logs table to store request data.

  3. Enable Middleware: Add LogApiRequest::class to the api middleware group in app/Http/Kernel.php:

    'api' => [
        \Illuminate\Routing\Middleware\ThrottleRequests::class,
        \CodeTech\ApiLogs\Http\Middleware\LogApiRequest::class, // <-- Add this line
        // ... other middleware
    ],
    
  4. First Use Case: Immediately start logging all API requests. No additional configuration is needed for basic usage. Logs will appear in the api_logs table with:

    • Request method (GET, POST, etc.)
    • URI
    • IP address
    • User agent
    • Timestamp
    • Input data (for non-GET requests)
    • Response status code

Implementation Patterns

Core Workflow

  1. Logging All API Requests: The middleware automatically logs every request routed through the api middleware group. No manual logging required in controllers.

  2. Customizing Logged Data: Extend the middleware to include additional fields. Override the LogApiRequest middleware in your project:

    namespace App\Http\Middleware;
    
    use CodeTech\ApiLogs\Http\Middleware\LogApiRequest as BaseLogApiRequest;
    
    class LogApiRequest extends BaseLogApiRequest
    {
        protected function getLogData()
        {
            $data = parent::getLogData();
            $data['custom_field'] = auth()->id(); // Example: Add user ID
            return $data;
        }
    }
    

    Update Kernel.php to use your custom middleware.

  3. Conditional Logging: Skip logging for specific routes by adding a skipApiLogging key to the route:

    Route::get('/skip-logging', function () {
        return response()->json(['message' => 'This won’t be logged']);
    })->middleware('skipApiLogging');
    

    Create a SkipApiLogging middleware to exclude routes.

  4. Querying Logs: Use Eloquent to fetch logs. The ApiLog model is available via:

    use CodeTech\ApiLogs\Models\ApiLog;
    
    $logs = ApiLog::where('status_code', 404)->latest()->get();
    
  5. Integration with Existing Systems:

    • Laravel Debugbar: Publish the package’s views to visualize logs in Debugbar:
      php artisan vendor:publish --provider="CodeTech\ApiLogs\Providers\ApiLogServiceProvider" --tag=views
      
    • Monitoring Tools: Export logs to external services (e.g., Datadog, Sentry) by hooking into the api.logged event:
      Event::listen('api.logged', function ($log) {
          // Send to external service
      });
      
  6. API Rate Limiting + Logging: Combine with throttle middleware to log rate-limited requests:

    Route::middleware(['throttle:60,1', 'logApiRequest'])->group(function () {
        // Rate-limited routes
    });
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Logging every request adds minimal overhead (~1-5ms per request), but avoid logging in high-throughput environments (e.g., WebSockets, real-time APIs). Use conditional middleware to exclude sensitive endpoints.
    • Fix: Add skipApiLogging middleware to critical paths.
  2. Sensitive Data Exposure:

    • Input data (e.g., passwords, tokens) is logged by default. This is a security risk.
    • Fix: Override getLogData() to sanitize inputs:
      protected function getLogData()
      {
          $data = parent::getLogData();
          unset($data['input']['password']); // Remove sensitive fields
          return $data;
      }
      
    • For GDPR compliance, consider hashing PII (Personally Identifiable Information).
  3. Migration Conflicts:

    • If the api_logs table already exists, the migration may fail. Use --force or manually merge columns:
      php artisan migrate --force
      
  4. Middleware Order Matters:

    • Place LogApiRequest after authentication middleware (e.g., auth:api) to include user context in logs:
      'api' => [
          \App\Http\Middleware\Authenticate::class,
          \CodeTech\ApiLogs\Http\Middleware\LogApiRequest::class, // <-- After auth
      ],
      
  5. Large Payloads:

    • Logging large request/response bodies (e.g., file uploads) can bloat the database.
    • Fix: Truncate or exclude large payloads:
      protected function getLogData()
      {
          $data = parent::getLogData();
          if (strlen(json_encode($data['input'])) > 1000) {
              $data['input'] = 'Large payload truncated';
          }
          return $data;
      }
      

Debugging Tips

  1. Verify Middleware is Active: Check if the middleware is registered in Kernel.php and that the route uses the api middleware group.

  2. Check Log Table: Inspect the api_logs table directly:

    php artisan tinker
    >>> \CodeTech\ApiLogs\Models\ApiLog::latest()->first();
    
  3. Event Listeners: Debug the api.logged event to ensure custom logic runs:

    Event::listen('api.logged', function ($log) {
        \Log::debug('Custom logic triggered for log ID: ' . $log->id);
    });
    
  4. Configuration Quirks:

    • The package uses Laravel’s default logging channels. If logs aren’t appearing, verify your config/logging.php settings.
    • For production, ensure the api_logs table is backed up regularly.

Extension Points

  1. Custom Log Model: Extend the ApiLog model to add scopes or accessors:

    namespace App\Models;
    
    use CodeTech\ApiLogs\Models\ApiLog as BaseApiLog;
    
    class ApiLog extends BaseApiLog
    {
        public function scopeFailed($query)
        {
            return $query->where('status_code', '>=', 400);
        }
    }
    
  2. Dynamic Logging: Conditionally log requests based on route attributes:

    Route::get('/admin', function () {
        return response()->json(['data' => 'admin']);
    })->middleware(['auth:admin', 'logApiRequest']);
    
  3. Log Retention: Add a scheduled task to purge old logs (e.g., older than 30 days):

    // app/Console/Kernel.php
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('api:purge-logs')->daily();
    }
    

    Publish the package’s commands:

    php artisan vendor:publish --provider="CodeTech\ApiLogs\Providers\ApiLogServiceProvider" --tag=commands
    
  4. Response Logging: Log response data by extending the middleware:

    protected function getLogData()
    {
        $data = parent::getLogData();
        $data['response'] = response()->getContent();
        return $data;
    }
    

    Warning: This can significantly increase storage usage. Use sparingly.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui