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 Log Viewer Laravel Package

root913/laravel-log-viewer

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require root913/laravel-log-viewer
    
  2. Register Service Provider: Add Rap2hpoutre\LaravelLogViewer\LaravelLogViewerServiceProvider::class to config/app.php under providers.

  3. Publish Config (Optional):

    php artisan vendor:publish --provider="Rap2hpoutre\LaravelLogViewer\LaravelLogViewerServiceProvider"
    

    This creates a config/log-viewer.php file for customization (e.g., log file paths, permissions).

  4. Route the Controller: Add this to your routes/web.php (or routes/api.php if needed):

    Route::get('/logs', 'Rap2hpoutre\LaravelLogViewer\LogViewerController@index');
    

    Protect this route with middleware (e.g., auth) in production.

  5. First Use Case: Visit /logs to view Laravel’s default log file (storage/logs/laravel.log). Filter by date, search for errors, or download logs.


Implementation Patterns

Core Workflows

  1. Log Inspection:

    • Real-time Filtering: Use the UI’s date picker or search bar to narrow down logs (e.g., 2023-10-01 or error).
    • Line-by-Line Analysis: Click a log entry to expand it and view context (previous/next lines).
    • Download Logs: Export logs as a .txt file for offline analysis.
  2. Integration with Existing Systems:

    • Log Rotation Compatibility: Works seamlessly with Laravel’s default log rotation (no extra config needed).
    • Custom Log Files: Override log-viewer.php to include additional log files (e.g., storage/logs/debug.log):
      'files' => [
          storage_path('logs/laravel.log'),
          storage_path('logs/debug.log'),
      ],
      
    • API Access: Extend the controller to expose logs via API (e.g., for monitoring tools):
      Route::get('/api/logs', [LogViewerController::class, 'apiIndex']);
      
  3. Development vs. Production:

    • Development: Use unprotected routes for quick debugging.
    • Production: Restrict access via middleware (e.g., auth:support) and log viewer usage to APP_DEBUG=true:
      if (!app()->environment('local') && !config('log-viewer.enabled')) {
          abort(403);
      }
      
  4. Automated Logging:

    • Log Critical Paths: Use Log::critical() for high-severity issues to ensure they appear prominently in the viewer.
    • Structured Logging: Leverage Laravel’s structured logging (e.g., Log::debug('User {id} logged in', ['id' => $user->id])) for easier filtering.

Advanced Patterns

  • Log Anonymization: Override the LogViewerController to sanitize sensitive data before rendering:

    public function index() {
        $logs = $this->getLogs();
        $sanitizedLogs = collect($logs)->map(fn($log) => str_replace('password=***', 'password=****', $log));
        return view('log-viewer::index', ['logs' => $sanitizedLogs]);
    }
    
  • Log Retention Policies: Combine with Laravel’s log-rotate package to auto-clean old logs and reduce viewer load.

  • Custom Views: Extend the default Blade template (resources/views/vendor/log-viewer/index.blade.php) to add:

    • Syntax highlighting for JSON/log context.
    • Collapsible sections for grouped logs (e.g., by request ID).

Gotchas and Tips

Pitfalls

  1. Permission Issues:

    • Symptom: Logs appear empty or return 403.
    • Fix: Ensure the web server user (e.g., www-data) has read access to storage/logs/:
      chmod -R 755 storage/logs/
      chown -R www-data:www-data storage/logs/
      
    • Tip: Use storage_path('logs') in log-viewer.php to avoid hardcoding paths.
  2. Log Rotation Conflicts:

    • Symptom: Viewer shows truncated logs after rotation.
    • Fix: Configure log-viewer.php to include rotated logs:
      'files' => [
          storage_path('logs/laravel-*.log'), // Wildcard for rotated files
      ],
      
    • Tip: Test with php artisan log:rotate before deploying.
  3. Performance with Large Logs:

    • Symptom: Slow loading or timeouts.
    • Fix:
      • Limit log retention (e.g., 30 days) in config/logging.php.
      • Use config('log-viewer.max_lines', 1000) to cap displayed logs.
      • Cache log summaries (e.g., daily error counts) in Redis.
  4. Middleware Conflicts:

    • Symptom: Routes fail silently.
    • Fix: Ensure the route isn’t overridden by other middleware (e.g., api routes). Use:
      Route::middleware(['web'])->get('/logs', [LogViewerController::class, 'index']);
      

Debugging Tips

  • Check Logs First: If the viewer fails, inspect storage/logs/laravel.log for errors like:

    [2023-10-01 12:00:00] local.ERROR: File not found at /path/to/log (View: /vendor/...)
    

    This often indicates a path or permission issue.

  • Disable Caching: Clear Laravel’s view cache if templates aren’t updating:

    php artisan view:clear
    
  • Test with Minimal Config: Reset log-viewer.php to defaults to isolate issues:

    return [
        'enabled' => true,
        'files' => [storage_path('logs/laravel.log')],
    ];
    

Extension Points

  1. Custom Log Formats: Override the LogViewerController to parse custom log formats (e.g., JSON):

    protected function parseLogLine($line) {
        $data = json_decode($line, true);
        return $data['message'] ?? $line;
    }
    
  2. Add Log Context: Extend the LogViewerController to include additional metadata (e.g., request IDs):

    public function index() {
        $logs = $this->getLogs();
        $enrichedLogs = array_map(function($log) {
            return [
                'line' => $log,
                'context' => $this->extractContext($log),
            ];
        }, $logs);
        return view('log-viewer::index', ['logs' => $enrichedLogs]);
    }
    
  3. Plugin Architecture: Create a trait for reusable log-viewer logic:

    namespace App\Traits;
    use Rap2hpoutre\LaravelLogViewer\LogViewerController as BaseController;
    
    trait LogViewerExtensions {
        protected function getLogs() {
            $logs = parent::getLogs();
            // Add custom logic (e.g., filter by IP)
            return $logs;
        }
    }
    

    Then use it in your controller:

    class CustomLogViewerController extends BaseController {
        use LogViewerExtensions;
    }
    
  4. Localization: Override the default Blade templates to support multiple languages:

    cp vendor/rap2hpoutre/laravel-log-viewer/resources/views/vendor/log-viewer/* resources/views/vendor/log-viewer/
    

    Then translate strings in resources/views/vendor/log-viewer/index.blade.php.

Configuration Quirks

  • enabled Flag: Disable the viewer in production by default (config('log-viewer.enabled', false)) and enable only for specific environments:

    'enabled' => app()->environment(['local', 'staging']),
    
  • File Path Wildcards: Use glob()-compatible patterns in log-viewer.php:

    'files' => [
        storage_path('logs/*.log'), // All log files
        storage_path('logs/error-*.log'), // Only error logs
    ],
    
  • Memory Limits: Large logs may hit PHP’s memory limit. Increase in .env:

    MEMORY_LIMIT=512M
    

    Or stream logs line-by-line in the controller:

    public function index() {
        $handle = fopen(storage_path('logs/laravel.log'), 'r');
        $logs = [];
        while (!feof($handle)) {
            $logs[] = fgets($handle);
        }
        fclose($handle);
        return view('log-viewer::index', ['logs' => $logs]);
    }
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours