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

Logging Laravel Package

unimontes-cead/logging

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require unimontes-cead/logging
    

    Publish the configuration file:

    php artisan vendor:publish --provider="Unimontes\Logging\LoggingServiceProvider" --tag="logging-config"
    
  2. Configuration Edit the published config file at config/logging-package.php to set:

    • enabled: Boolean to toggle the package.
    • webhook_url: The endpoint of your internal logging system.
    • log_level: Minimum log level to forward (e.g., debug, info, error).
    • ignore_exceptions: Array of exception classes to exclude from logging.
  3. First Use Case Enable the package in config/logging-package.php and test by logging a message:

    \Log::info('Test message from Laravel to internal logging system');
    

    Verify the message appears in your internal logging system.


Implementation Patterns

Core Workflows

  1. Logging Integration

    • Use Laravel’s built-in \Log facade (e.g., debug(), info(), error()) as usual. The package intercepts logs matching the configured level and forwards them.
    • Example:
      try {
          $result = riskyOperation();
      } catch (\Exception $e) {
          \Log::error('Operation failed', ['exception' => $e, 'context' => ['user_id' => 123]]);
      }
      
  2. Contextual Logging Attach structured metadata to logs for better traceability:

    \Log::info('User action', [
        'user_id' => auth()->id(),
        'action' => 'profile_update',
        'ip' => request()->ip(),
    ]);
    
  3. Exception Handling Automatically log exceptions (unless ignored):

    // In AppServiceProvider::boot()
    \App\Services\LoggingService::logExceptions();
    
  4. Conditional Logging Disable logging for specific environments (e.g., local):

    if (app()->environment('production')) {
        \Log::info('Production-only log');
    }
    

Advanced Patterns

  • Custom Log Channels Extend the package to support additional channels (e.g., Slack, Datadog) by creating a custom channel in app/Providers/AppServiceProvider.php:

    use Unimontes\Logging\Channels\WebhookChannel;
    
    \Log::extend('webhook', function ($app) {
        return new WebhookChannel($app['config']['logging-package.webhook_url']);
    });
    
  • Middleware for API Logging Log incoming requests in a Laravel middleware:

    public function handle($request, Closure $next) {
        \Log::info('API Request', [
            'method' => $request->method(),
            'path' => $request->path(),
            'input' => $request->all(),
        ]);
        return $next($request);
    }
    
  • Queue-Based Logging Offload logging to a queue to avoid blocking requests:

    \Log::build([
        'driver' => 'single',
        'level' => 'debug',
        'handler' => \Monolog\Handler\SyslogUdpHandler::class,
    ])->pushHandler(new \Unimontes\Logging\Handlers\WebhookHandler(config('logging-package.webhook_url')));
    

Gotchas and Tips

Pitfalls

  1. Configuration Overrides

    • Ensure config/logging-package.php is not overridden by environment-specific configs (e.g., .env). Use config('logging-package.enabled') to dynamically check the setting.
  2. Webhook Rate Limits

    • If the internal logging system has rate limits, buffer logs using Laravel queues or a local cache (e.g., Redis) before forwarding.
  3. Sensitive Data Leaks

    • Avoid logging raw user input or passwords. Sanitize data before logging:
      \Log::info('User input', [
          'email' => $request->input('email'),
          'password' => '[REDACTED]', // Never log passwords!
      ]);
      
  4. Log Level Mismatches

    • If logs aren’t appearing, verify:
      • The log_level in config/logging-package.php matches the severity of your test logs (e.g., debug vs. info).
      • The webhook URL is correct and accessible from your Laravel environment.
  5. Exception Ignoring

    • If exceptions aren’t logging as expected, check the ignore_exceptions array in the config. Use fully qualified class names (e.g., \App\Exceptions\ValidationException).

Debugging Tips

  • Enable Debug Mode Temporarily set APP_DEBUG=true in .env to see Monolog’s internal logs:

    \Log::debug('Debug message', ['context' => 'test']);
    
  • Check Webhook Responses Use Laravel’s HTTP client to test the webhook manually:

    $response = Http::post(config('logging-package.webhook_url'), [
        'message' => 'Test',
        'context' => ['test' => true],
    ]);
    
  • Log Handler Verification Inspect the active handlers in a Tinker session:

    php artisan tinker
    >>> \Log::getMonolog()->getHandlers()
    

Extension Points

  1. Custom Log Format Override the log format in AppServiceProvider::boot():

    $monolog = \Log::getMonolog();
    $monolog->pushHandler(new \Monolog\Handler\StreamHandler(storage_path('logs/custom.log')));
    $monolog->pushProcessor(function ($record) {
        $record['extra']['custom_field'] = 'value';
        return $record;
    });
    
  2. Add Metadata to All Logs Inject user or request context globally:

    \Log::build([
        'driver' => 'stack',
        'handler' => \Monolog\Handler\StreamHandler::class,
    ])->pushHandler(new \Unimontes\Logging\Handlers\WebhookHandler(config('logging-package.webhook_url')));
    
    \Log::withContext(['user_id' => auth()->id()]);
    
  3. Logging to Multiple Systems Combine the package with other logging drivers (e.g., Stack):

    'logging' => [
        'default' => 'stack',
        'channels' => [
            'stack' => [
                'driver' => 'stack',
                'channels' => ['single', 'webhook'],
            ],
            'webhook' => [
                'driver' => 'custom',
                'via' => \Unimontes\Logging\LoggingChannel::class,
            ],
        ],
    ],
    
  4. Logging Database Queries Use Laravel’s query logging and forward it:

    \DB::enableQueryLog();
    // Perform queries...
    \Log::info('Queries', ['queries' => \DB::getQueryLog()]);
    
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle