Weave 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

Sdk Core Laravel Package

applogger/sdk-core

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require applogger/sdk-core
    

    Requires PHP 8.3+.

  2. Initialize the SDK (in your application bootstrap, e.g., bootstrap/app.php or index.php):

    use AppLogger\SdkCore\Client;
    
    $client = Client::initialize('YOUR_API_KEY');
    

    Replace YOUR_API_KEY with your AppLogger project key (found in the dashboard).

  3. First Use Case: Capture an Exception

    try {
        // Risky operation
        $result = riskyOperation();
    } catch (\Exception $e) {
        $client->captureException($e);
    }
    

    The exception will be sent to AppLogger with automatic fingerprinting and deduplication.

  4. First Use Case: Log a Message

    $logger = $client->logger();
    $logger->error('User login failed', [
        'user_id' => 123,
        'ip' => $_SERVER['REMOTE_ADDR'],
    ]);
    

    Logs will be structured and sent to AppLogger’s log aggregation pipeline.


Implementation Patterns

Core Workflows

1. Exception and Error Handling

  • Automatic Capture: Enable the global error handler via default_integrations (enabled by default):

    $client = Client::initialize('API_KEY', [
        'default_integrations' => [
            'error_handler' => true,
            'shutdown_handler' => true,
        ],
    ]);
    
    • Catches uncaught exceptions, fatal errors, and out-of-memory (OOM) errors.
    • Uses MemoryReservation to preserve error context during shutdown.
  • Manual Capture: For controlled scenarios:

    $client->captureException($exception, [
        'tags' => ['auth', 'failed'],
        'user' => ['id' => 123, 'email' => '[email protected]'],
    ]);
    

2. Structured Logging

  • Use the PSR-3 LoggerInterface for structured logs:
    $logger = $client->logger();
    $logger->info('Order processed', [
        'order_id' => $order->id,
        'amount' => $order->amount,
        'metadata' => $order->metadata,
    ]);
    
  • Contextual Logging: Attach global context (e.g., user, request ID) via configureScope:
    $client->configureScope([
        'user_id' => auth()->id(),
        'request_id' => request()->header('X-Request-ID'),
    ]);
    

3. Breadcrumbs and Debugging

  • Add breadcrumbs for debugging flows:
    $client->addBreadcrumb('Button clicked', [
        'button' => 'submit',
        'timestamp' => time(),
    ]);
    
  • Use withScope for temporary context:
    $client->withScope(['feature_flag' => true], function () {
        // Logs/scopes here will include feature_flag=true
        $client->captureMessage('Feature X triggered');
    });
    

4. Delivery Modes

  • The SDK auto-detects your runtime (CLI, FastCGI, Swoole, etc.) and flushes logs/errors appropriately:

    • Web (FastCGI/PSR-15): Flushes after response (non-blocking).
    • CLI/Workers (Swoole/RoadRunner): Flushes on shutdown or explicitly via flush().
    • FrankenPHP: Optimized for its event loop.
  • Force an immediate flush (e.g., for CLI scripts):

    $client->flush();
    

5. Data Scrubbing (GDPR)

  • Automatically scrub sensitive data (e.g., passwords, tokens) in logs/exceptions:
    $client = Client::initialize('API_KEY', [
        'data_scrubbing' => [
            'fields' => [
                'password' => true,
                'api_key' => true,
                'token' => true,
            ],
        ],
    ]);
    
  • Custom scrubbers:
    $client->addDataScrubber(function ($value) {
        return str_repeat('*', strlen($value));
    }, 'credit_card');
    

Integration Tips

Laravel-Specific

While this is framework-agnostic, Laravel users can:

  1. Bootstrap in AppServiceProvider:
    public function boot()
    {
        $client = Client::initialize(config('applogger.key'));
        $this->app->singleton('applogger', fn() => $client);
    }
    
  2. Middleware for Request Context:
    public function handle($request, Closure $next)
    {
        $client = app('applogger');
        $client->configureScope([
            'user_id' => auth()->id(),
            'path' => $request->path(),
        ]);
        return $next($request);
    }
    
  3. Exception Handler:
    public function report(Throwable $exception)
    {
        app('applogger')->captureException($exception);
    }
    

PSR-18 HTTP Client

The SDK uses PSR-18 for HTTP requests. Customize the client (e.g., for proxies):

use AppLogger\SdkCore\Client;
use Http\Client\Common\Plugin\HeaderAppendPlugin;
use Http\Client\Common\Plugin\HeaderSetPlugin;
use Http\Client\Common\PluginClient;

$httpClient = new PluginClient(
    new \GuzzleHttp\Client(),
    [
        new HeaderSetPlugin('User-Agent', 'MyApp/1.0'),
    ]
);

$client = Client::initialize('API_KEY', [
    'http_client' => $httpClient,
]);

Gotchas and Tips

Pitfalls

  1. Shutdown Handler Conflicts:

    • If another library registers a shutdown handler (e.g., Monolog), the SDK’s handler may not trigger. Disable the SDK’s handler if needed:
      $client = Client::initialize('API_KEY', [
          'default_integrations' => [
              'shutdown_handler' => false,
          ],
      ]);
      
  2. Memory Leaks in Long-Running Processes:

    • The SDK buffers events in memory. For CLI workers or long-running scripts, call flush() periodically or disable buffering:
      $client = Client::initialize('API_KEY', [
          'buffer_events' => false,
      ]);
      
  3. Sensitive Data in Breadcrumbs:

    • Breadcrumbs are sent with every event. Avoid adding PII or tokens:
      // Bad: Adds token to every subsequent event
      $client->addBreadcrumb('API call', ['token' => $user->api_token]);
      
      // Good: Scrub or omit sensitive data
      $client->addBreadcrumb('API call', ['endpoint' => '/user/data']);
      
  4. FastCGI/FPM Timeouts:

    • If your web server times out before the SDK flushes, increase the timeout or use flush() in a deferred block (Laravel):
      \Illuminate\Support\Facades\Deferred::after(function () {
          app('applogger')->flush();
      });
      
  5. Double Initialization:

    • Calling Client::initialize() multiple times creates separate instances. Use a singleton pattern (e.g., Laravel’s app() binding) to reuse the client.

Debugging

  1. Enable Debug Logging:

    • Set the debug config to log SDK activity to stderr:
      $client = Client::initialize('API_KEY', [
          'debug' => true,
      ]);
      
    • Check logs for issues like failed HTTP requests or serialization errors.
  2. Validate API Key:

    • Test with a dummy key first to ensure the SDK is working:
      $client->captureMessage('Test event', ['key' => 'dummy']);
      
    • Verify events appear in the AppLogger dashboard (even if invalid).
  3. Network Issues:

    • The SDK retries failed requests (exponential backoff). To debug:
      • Check http_client errors in debug logs.
      • Temporarily disable retries:
        $client = Client::initialize('API_KEY', [
            'retry_policy' => ['max_attempts' => 0],
        ]);
        
  4. Event Deduplication:

    • If events appear duplicated, check:
      • The fingerprint config (default: SHA-256 of the message).
      • Whether captureException is called multiple times for the same exception.

Tips

  1. Environment-Specific Config:

    • Use different API keys for dev/staging/prod:
      $client = Client::initialize(env('APPLOGGER_KEY'));
      
  2. Performance Optimization:

    • Batch events by disabling auto-flushing (for high-throughput apps):
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.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
adachsoft/php-code-style