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

apextoolbox/symfony-logger

View on GitHub
Deep Wiki
Context7

Getting Started

Install via Composer:

composer require vendor/package-name

Publish the configuration and migration:

php artisan vendor:publish --provider="Vendor\PackageName\PackageServiceProvider" --tag="config"
php artisan vendor:publish --provider="Vendor\PackageName\PackageServiceProvider" --tag="migrations"
php artisan migrate

First Use Case: Enable logging for a specific route by adding middleware:

Route::get('/tracked-endpoint', function () {
    return response()->json(['data' => 'test']);
})->middleware(\Vendor\PackageName\Http\Middleware\TrackRequest::class);

Configure sensitive data filtering in config/package-name.php:

'sensitive_data' => [
    'exclude_headers' => ['authorization', 'cookie'],
    'mask_fields' => ['password', 'credit_card'],
],

Implementation Patterns

Core Workflows

  1. Request/Response Logging:

    • Automatically captures all HTTP requests/responses via middleware. No manual instrumentation needed.
    • Use TrackRequest middleware globally or selectively via route middleware.
  2. Log Collection:

    • Integrates with Monolog via IntrospectionProcessor. Logs automatically include:
      • Source class/method
      • Call type (e.g., debug(), error())
    • Example usage:
      \Log::debug('User action', ['user_id' => $user->id]);
      
  3. Exception Tracking:

    • Unhandled exceptions are captured with:
      • Full stack trace
      • Source code context (if available)
      • Deduplication hash (to avoid duplicates)
    • Override default handler in App\Exceptions\Handler:
      public function report(Throwable $exception)
      {
          if (!app()->bound('package-name')) {
              return parent::report($exception);
          }
      }
      
  4. Outgoing HTTP Requests:

    • Decorates HttpClient automatically. Logs include:
      • URL, method, headers, body
      • Timing metrics (connect/read time)
    • Example:
      $client = app(\Vendor\PackageName\Http\Client::class);
      $response = $client->get('https://api.example.com/data');
      
  5. Doctrine Query Logging:

    • Enable via config:
      'doctrine' => [
          'enabled' => true,
          'log_query_params' => env('DB_LOG_PARAMS', false),
      ],
      
    • Works with both DBAL 3.x and 4.x.
  6. Console/Queue Tracking:

    • Logs from Artisan commands and Messenger workers are captured automatically.
    • No additional setup required.

Integration Tips

  • Path Filtering: Control which routes are tracked via config:
    'path_filtering' => [
        'include' => ['/api/*', '/admin/*'],
        'exclude' => ['/health', '/ping'],
    ],
    
  • Sensitive Data: Extend masking rules via service provider:
    $this->app->extend('package-name.sensitive-data', function ($resolver) {
        $resolver->addMaskRule('new_field', 'custom_regex');
        return $resolver;
    });
    
  • Async Delivery: Configure timeouts in config/package-name.php:
    'async' => [
        'connect_timeout' => 5, // seconds
        'read_timeout' => 10,   // seconds
    ],
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Async delivery is designed to minimize blocking, but heavy logging (e.g., large payloads) may still impact performance.
    • Mitigation: Use path filtering to exclude high-traffic, low-value routes.
  2. Sensitive Data Leaks:

    • Default masking rules may not cover all edge cases. Always validate:
      • Headers (e.g., x-api-key).
      • Response bodies (e.g., JSON fields like user.token).
    • Tip: Test with tinker to verify masking:
      php artisan tinker
      >>> \Vendor\PackageName\Support\Facades\SensitiveData::mask('{"token":"abc123"}');
      
  3. Doctrine Conflicts:

    • If using both doctrine/dbal and eloquent, ensure the package’s event listeners are registered after Eloquent’s.
    • Fix: Override the service provider binding in AppServiceProvider:
      public function register()
      {
          $this->app->bind(
              \Vendor\PackageName\Doctrine\Listener::class,
              function ($app) { return new \Vendor\PackageName\Doctrine\Listener($app['db']); }
          );
      }
      
  4. Async Delivery Failures:

    • If the async endpoint is unreachable, logs/exceptions will not be retried by default.
    • Workaround: Implement a fallback queue (e.g., sync delivery) in config/package-name.php:
      'async' => [
          'fallback_to_sync' => env('PACKAGE_NAME_FALLBACK', false),
      ],
      

Debugging

  • Log Inspection:

    • Check raw payloads before async delivery in storage/logs/package-name-debug.log.
    • Enable debug mode in config:
      'debug' => env('APP_DEBUG', false),
      
  • Stack Trace Context:

    • Source code context for exceptions may fail if:
      • The project uses a non-standard autoloader.
      • The exception occurs in a compiled file (e.g., vendor/).
    • Solution: Exclude such paths from context logging:
      'exception_context' => [
          'exclude_paths' => [
              'vendor/',
              'bootstrap/cache/',
          ],
      ],
      

Extension Points

  1. Custom Payload Transformers:

    • Extend Vendor\PackageName\PayloadTransformer to modify payloads before async delivery:
      $this->app->bind(\Vendor\PackageName\PayloadTransformer::class, function ($app) {
          return new class($app['package-name.transformer']) implements \Vendor\PackageName\Contracts\PayloadTransformer {
              public function transform(array $payload): array
              {
                  $payload['custom_field'] = 'value';
                  return parent::transform($payload);
              }
          };
      });
      
  2. Webhook Fallback:

    • Replace the async curl delivery with a queue job or webhook:
      $this->app->singleton(\Vendor\PackageName\Async\Delivery::class, function ($app) {
          return new \App\Services\CustomDelivery($app['package-name.config']);
      });
      
  3. Path Filtering Callbacks:

    • Dynamically include/exclude routes via a callback:
      'path_filtering' => [
          'callback' => function ($request) {
              return $request->user()?->isAdmin();
          },
      ],
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky