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

Flare Client Php Laravel Package

spatie/flare-client-php

PHP 8.2+ client for sending exceptions, errors, and stack traces to Flare. Install via Composer and use in any PHP app; Laravel users should use spatie/laravel-flare. Includes docs, tests, and ongoing maintenance by Spatie.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require spatie/flare-client-php

For Laravel, prefer spatie/laravel-flare for seamless integration.

  1. Configuration: Add your Flare API key to .env:

    FLARE_API_KEY=your_api_key_here
    
  2. First Use Case: Capture an exception in a controller or service:

    use Spatie\FlareClient\Flare;
    
    try {
        // Risky operation
    } catch (\Exception $e) {
        Flare::report($e); // Sends to Flare
    }
    
  3. Key Classes:

    • Flare: Main entry point for reporting errors, logs, and traces.
    • Flare::report(): Send exceptions/errors.
    • Flare::log(): Log messages with levels (e.g., Flare::log('Debug', 'Message')).
    • Flare::tracer(): Start/manage traces (e.g., Flare::tracer()->startSpan('operation')).
  4. Where to Look First:


Implementation Patterns

Core Workflows

1. Error Reporting

  • Basic:
    try {
        // Code that may fail
    } catch (\Exception $e) {
        Flare::report($e); // Auto-captures stack traces, context, etc.
    }
    
  • Custom Context:
    Flare::report($e)
        ->withAttribute('user_id', auth()->id())
        ->withAttribute('custom_data', ['key' => 'value']);
    

2. Distributed Tracing

  • Start a Trace:
    $trace = Flare::tracer()->startTrace('user-purchase');
    
  • Add Spans:
    $span = $trace->startSpan('process-payment');
    // Business logic...
    $span->end();
    $trace->end();
    
  • Subtasks (Nested Traces):
    $parentTrace = Flare::tracer()->getCurrentTrace();
    $childTrace = Flare::tracer()->startTrace('child-operation', parent: $parentTrace);
    

3. Logging

  • Structured Logs:
    Flare::log('info', 'Order processed', [
        'order_id' => 123,
        'user_id' => auth()->id(),
    ]);
    
  • Log Levels: Use Monolog’s Level enum (Flare::log(Monolog\Level::Error, 'Message')).

4. Sampling (Performance Optimization)

  • Dynamic Sampling:
    Flare::sampler()->addRule(
        SamplingRule::create()
            ->forEntryPoint('checkout')
            ->sample(100) // 100% sampling for checkout flows
    );
    
  • Entry Points: Define where traces start (e.g., routes, commands):
    Flare::entryPointResolver()->addEntryPoint(
        EntryPoint::route('checkout.store')
    );
    

5. Attribute Providers (Context Enrichment)

  • Custom Providers:
    Flare::requestAttributesProvider(fn () => [
        'custom_metric' => request()->ip(),
    ]);
    
  • Built-in Providers:
    • RequestAttributesProvider
    • RouteAttributesProvider
    • JobAttributesProvider (for queues)
    • UserAttributesProvider

6. Queue/Job Monitoring

  • Queue Recorder:
    Flare::queueRecorder()->recordJob($job, $payload);
    
  • Subtask Mode:
    Flare::tracer()->startTrace('job', subtask: true);
    

7. Lifecycle Management

  • Flush Reports:
    Flare::lifecycle()->flush(); // Manually trigger sends
    
  • Reset State:
    Flare::lifecycle()->reset(); // Clear in-memory state
    

Integration Tips

Laravel-Specific

  • Exception Handler: Override App\Exceptions\Handler to auto-report:
    public function report(Throwable $exception) {
        if (! app()->bound('flare')) return;
        app('flare')->report($exception);
    }
    
  • Middleware: Use FlareMiddleware (from laravel-flare) to auto-capture HTTP errors.

Symfony

  • Kernel Events: Listen to kernel.exception to report errors:
    $event->getThrowable(); // Report via Flare
    

Testing

  • Test Traces:
    php artisan flare:test
    
    Or programmatically:
    Flare::testTrace()->startTrace('test-operation');
    

Performance

  • Daemon Fallback: The package uses a local DaemonSender by default. Ensure the Flare daemon is running for offline buffering.

Gotchas and Tips

Pitfalls

  1. Sampling Misconfiguration:

    • Issue: Traces not appearing in Flare despite errors.
    • Fix: Verify SamplingRules cover your entry points:
      Flare::sampler()->addRule(
          SamplingRule::create()->sample(100) // Ensure this matches your use case
      );
      
    • Debug: Check Flare::ids()->traceId to confirm traces are generated.
  2. Attribute Overrides:

    • Issue: Custom attributes being ignored.
    • Fix: Ensure providers are registered before the trace/log is recorded:
      Flare::requestAttributesProvider(fn () => ['key' => 'value']);
      Flare::report($e); // Now includes the attribute
      
  3. Subtask Mode Not Working:

    • Issue: Jobs/commands starting new traces instead of attaching to parent.
    • Fix: Explicitly set subtask: true:
      Flare::tracer()->startTrace('job', subtask: true);
      
  4. Daemon Unreachable:

    • Issue: Reports not sending during daemon downtime.
    • Fix: The package falls back to HTTP. Check logs for DaemonSender errors.
  5. Sensitive Data Leakage:

    • Issue: Accidental exposure of passwords/tokens in logs.
    • Fix: Use censoring for request/response bodies:
      Flare::ignoreRequestBody(); // Globally
      Flare::ignoreResponseBody(); // Globally
      
      Or per-field:
      Flare::ignoreRequestBodyFields(['password', 'credit_card']);
      
  6. PHP 8.4+ Deprecations:

    • Issue: implictly nullable or non-scalar type errors.
    • Fix: Update to v3.x+ (fixed in v1.9.0).
  7. Grouping Overrides:

    • Issue: Errors not grouping as expected (e.g., same stacktrace but different codes).
    • Fix: Use FullStacktraceAndExceptionClassAndCode:
      Flare::report($e)->withGroupingOverride(
          GroupingOverride::fullStacktraceAndExceptionClassAndCode()
      );
      

Debugging Tips

  1. Check Sent Reports:

    dd(Flare::sentReports()); // Inspect before sending
    
  2. Enable Verbose Logging:

    Flare::logger()->setLevel(Monolog\Level::Debug);
    
  3. Inspect Trace IDs:

    $traceId = Flare::ids()->traceId;
    // Use in logs for correlation
    
  4. Disable Flare Temporarily:

    Flare::disable(); // Skip all reporting
    
  5. Validate API Key:

    • Ensure FLARE_API_KEY is correct and the key has permissions in Flare’s dashboard.

Extension Points

  1. Custom Recorders:

    • Implement RecorderInterface to add new data sources (e.g., database queries):
      Flare::addRecorder(new class implements RecorderInterface {
          public function record(RecorderData $data) { /* ... */ }
      });
      
  2. Attribute Providers:

    • Extend existing providers (e.g., add team info):
      Flare::
      
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony