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

Symfony Logger Client Laravel Package

dennisvanbeersel/symfony-logger-client

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

Since this is a Symfony bundle, Laravel integration requires Symfony Bridge or Laravel Symfony Integration (e.g., spatie/laravel-symfony-support). Start with:

composer require dennisvanbeersel/symfony-logger-client spatie/laravel-symfony-support
  1. Publish Config Copy the bundle’s config to Laravel’s config:

    php artisan vendor:publish --provider="DennisVanBeersel\ApplicationLogger\ApplicationLoggerBundle" --tag="config"
    

    Update .env with:

    APPLICATION_LOGGER_DSN=https://applogger.eu/your-project-uuid
    APPLICATION_LOGGER_API_KEY=your-64-char-key
    
  2. Register Bundle In config/app.php, add the bundle to providers:

    DennisVanBeersel\ApplicationLogger\ApplicationLoggerBundle::class,
    
  3. First Log Use the ApplicationLogger service in a controller or service:

    use DennisVanBeersel\ApplicationLogger\ApplicationLogger;
    
    public function __construct(private ApplicationLogger $logger) {}
    
    public function handleError() {
        $this->logger->error('Test error', [
            'context' => ['user_id' => auth()->id(), 'trace' => true],
        ]);
    }
    

Implementation Patterns

Core Workflows

  1. Error Tracking

    • Exceptions: Wrap try-catch blocks with $logger->error():
      try {
          $user->delete();
      } catch (\Exception $e) {
          $this->logger->error('Failed to delete user', [
              'exception' => $e,
              'user_id' => $user->id,
          ]);
      }
      
    • HTTP Errors: Log failed API calls with status codes:
      $this->logger->error('API request failed', [
          'url' => $request->url(),
          'status' => $response->status(),
          'response' => $response->body(),
      ]);
      
  2. Performance Monitoring

    • Track slow queries or routes:
      $this->logger->performance('slow_query', [
          'query' => $sql,
          'duration_ms' => $executionTime,
      ]);
      
  3. Contextual Logging

    • Attach user sessions, request data, or debug bars:
      $this->logger->info('User action', [
          'user' => auth()->user()->toArray(),
          'request' => request()->except(['password']),
      ]);
      
  4. JavaScript Integration

    • Use the bundled JS SDK to log frontend errors (see README).

Laravel-Specific Patterns

  1. Service Provider Hooks

    • Override the logger in AppServiceProvider:
      public function boot() {
          $this->app->bind(ApplicationLogger::class, function ($app) {
              return new ApplicationLogger(
                  $app->make('config')->get('application_logger.dsn'),
                  $app->make('config')->get('application_logger.api_key')
              );
          });
      }
      
  2. Event Listeners

    • Log exceptions globally via HandleExceptions:
      use Symfony\Component\HttpKernel\Event\ExceptionEvent;
      
      public function __invoke(ExceptionEvent $event) {
          $this->logger->error('Unhandled exception', [
              'exception' => $event->getThrowable(),
              'url' => $event->getRequest()->getUri(),
          ]);
      }
      
  3. Queue Failed Jobs

    • Log failed queue jobs in FailedJob:
      public function handle(FailedJob $event) {
          $this->logger->error('Job failed', [
              'job' => $event->job,
              'exception' => $event->exception,
          ]);
      }
      

Gotchas and Tips

Pitfalls

  1. DSN/API Key Validation

    • The bundle silently fails if dsn or api_key is invalid. Validate in config/packages/application_logger.yaml:
      application_logger:
          dsn: '%env(APPLICATION_LOGGER_DSN)%'
          api_key: '%env(APPLICATION_LOGGER_API_KEY)%'
          validate_credentials: true  # Add this line
      
    • Check logs for Connection refused or Invalid API key errors.
  2. Rate Limiting

    • The service may throttle requests. Use async: true to queue logs:
      application_logger:
          async: true
      
    • Monitor failed_jobs table for queued-but-failed logs.
  3. Sensitive Data Leaks

    • Never log:
      • Passwords, tokens, or PII (use mask: true for fields like emails).
      • Database credentials or API secrets.
    • Example:
      $this->logger->error('Login failed', [
          'email' => ['value' => $email, 'mask' => true],
      ]);
      
  4. Symfony Dependency Conflicts

    • If using Laravel’s Log facade, avoid mixing with this bundle’s logger. Use ApplicationLogger exclusively for error tracking.

Debugging Tips

  1. Enable Debug Mode Set debug: true in config to log HTTP errors to Symfony’s profiler:

    application_logger:
        debug: true
    
  2. Check HTTP Requests Use strace or tcpdump to verify logs reach the endpoint:

    strace -f -e trace=network php artisan tinker
    
  3. Test Locally Mock the logger in tests:

    $this->app->instance(ApplicationLogger::class, Mockery::mock(ApplicationLogger::class));
    

Extension Points

  1. Custom Log Levels Extend the bundle by adding a custom level (e.g., security):

    $this->logger->custom('security', 'Unauthorized access', ['ip' => request()->ip()]);
    

    Requires server-side support (contact maintainers).

  2. Webhook Integration Use Laravel’s queue:work to process logs and forward them to other services (e.g., Slack, Datadog):

    $this->app->bind(ApplicationLogger::class, function ($app) {
        $logger = new ApplicationLogger(...);
        $logger->setWebhookHandler(function ($log) {
            // Forward to your webhook
        });
        return $logger;
    });
    
  3. Breadcrumbs Add context to logs via middleware:

    public function handle($request, Closure $next) {
        $this->logger->addBreadcrumb('route', $request->route()->getName());
        return $next($request);
    }
    
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.
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
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