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

Log Viewer Laravel Laravel Package

sdtech/log-viewer-laravel

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require sdtech/log-viewer-laravel
    
  2. Publish the config and migration:
    php artisan vendor:publish --provider="SDTech\LogViewer\LogViewerServiceProvider" --tag="config"
    php artisan vendor:publish --provider="SDTech\LogViewer\LogViewerServiceProvider" --tag="migrations"
    
  3. Run migrations:
    php artisan migrate
    
  4. Add routes (in routes/web.php):
    Route::middleware(['web', 'auth'])->group(function () {
        Route::get('/logs', [\SDTech\LogViewer\Http\Controllers\LogViewerController::class, 'index']);
    });
    

First Use Case

  • View logs: Navigate to /logs (requires auth middleware). The package provides a filtered, searchable UI for all stored logs.
  • Quick troubleshooting: Use the search bar to filter by error messages, timestamps, or context (e.g., Exception, debug).

Implementation Patterns

Core Workflows

  1. Log Storage Integration

    • Override Laravel’s default logger to store logs in the database. Add this to config/logging.php:
      'channels' => [
          'log_viewer' => [
              'driver' => 'custom',
              'via' => \SDTech\LogViewer\LogChannels\LogViewerChannel::class,
          ],
      ],
      
    • Use the channel in config/app.php under logging.default.
  2. Filtering and Search

    • Leverage the built-in UI filters (e.g., level, date range, context). For custom filters, extend the controller:
      public function index(Request $request)
      {
          $logs = \SDTech\LogViewer\Models\Log::query()
              ->when($request->has('custom_filter'), function ($query) use ($request) {
                  return $query->where('message', 'like', '%' . $request->custom_filter . '%');
              })
              ->paginate(50);
          return view('log-viewer::index', compact('logs'));
      }
      
  3. Log Management

    • Clear logs: Use the LogViewerController method:
      public function clear(Request $request)
      {
          \SDTech\LogViewer\Models\Log::truncate();
          return back()->with('success', 'Logs cleared!');
      }
      
    • Download logs: Implement a custom download route:
      Route::get('/logs/download', function () {
          return \SDTech\LogViewer\Http\Controllers\LogViewerController::downloadLogs();
      });
      
  4. Real-Time Monitoring

    • Pair with Laravel Echo/Pusher to stream new logs to the UI. Example:
      Echo.channel('logs')
          .listen('LogStored', (e) => {
              // Append new log to UI dynamically
          });
      
      (Requires extending the package to emit events.)

Gotchas and Tips

Pitfalls

  1. Performance with Large Logs

    • Issue: Querying millions of logs may time out or freeze the UI.
    • Fix: Add database indexes to created_at, level, and context columns:
      Schema::table('logs', function (Blueprint $table) {
          $table->index('level');
          $table->index('context');
      });
      
    • Tip: Use pagination (->paginate(50)) and lazy-load logs.
  2. Log Retention

    • Issue: Database bloat from retained logs.
    • Fix: Implement a cron job to purge old logs (e.g., older than 30 days):
      php artisan schedule:run
      
      Add to app/Console/Kernel.php:
      protected function schedule(Schedule $schedule)
      {
          $schedule->command(LogViewerPurgeCommand::class)->daily();
      }
      
  3. Middleware Conflicts

    • Issue: Routes may not load if auth middleware is misconfigured.
    • Fix: Ensure the route group includes web middleware (handles sessions):
      Route::middleware(['web', 'auth'])->group(...);
      
  4. Log Channel Misconfiguration

    • Issue: Logs not appearing in the UI.
    • Debug: Verify the log_viewer channel is set as default in config/app.php and that the LogViewerChannel is properly registered.

Extension Points

  1. Custom Log Fields

    • Extend the Log model to add metadata (e.g., user_id, ip_address):
      public function setIpAttribute($value)
      {
          $this->attributes['ip_address'] = $value;
      }
      
    • Update the migration and UI views accordingly.
  2. Log Anonymization

    • Sanitize sensitive data (e.g., passwords, tokens) before storage:
      use SDTech\LogViewer\LogChannels\LogViewerChannel;
      
      class CustomLogViewerChannel extends LogViewerChannel
      {
          protected function prepareLog(array $log)
          {
              $log['message'] = str_replace('password=.*&', 'password=***&', $log['message']);
              return parent::prepareLog($log);
          }
      }
      
  3. API Access

    • Expose log endpoints via API for external tools:
      Route::middleware('api')->get('/api/logs', [LogViewerController::class, 'apiIndex']);
      
      Update the controller to return JSON:
      public function apiIndex(Request $request)
      {
          return \SDTech\LogViewer\Models\Log::query()
              ->filter($request)
              ->paginate(50)
              ->toJson();
      }
      
  4. Testing

    • Mock log storage in tests:
      use SDTech\LogViewer\Models\Log;
      
      public function test_log_storage()
      {
          Log::factory()->create(['message' => 'Test log']);
          $this->assertDatabaseHas('logs', ['message' => 'Test log']);
      }
      
    • Use Log::flush() to clear test logs between tests.
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