Skip to content

API Reference

Jean-Marc Strauven edited this page Aug 1, 2025 · 2 revisions

API Reference

This guide provides reference documentation for Laravel ChronoTrace's programmatic API.

Service Classes

TraceRecorder

The main service for recording traces programmatically.

use Grazulex\LaravelChronotrace\Services\TraceRecorder;

$recorder = app(TraceRecorder::class);

Methods

startRecording(): void

Start recording a new trace.

$recorder->startRecording();

stopRecording(): ?string

Stop recording and return the trace ID.

$traceId = $recorder->stopRecording();

isRecording(): bool

Check if currently recording.

if ($recorder->isRecording()) {
    // Recording is active
}

captureEvent(string $type, array $data): void

Manually capture a custom event.

$recorder->captureEvent('custom', [
    'action' => 'user_login',
    'user_id' => 123,
    'timestamp' => microtime(true),
]);

TraceStorage

Interface for storing and retrieving traces.

use Grazulex\LaravelChronotrace\Storage\TraceStorage;

$storage = app(TraceStorage::class);

Methods

store(string $traceId, array $data): bool

Store a trace.

$success = $storage->store($traceId, $traceData);

retrieve(string $traceId): ?TraceData

Retrieve a trace by ID.

$trace = $storage->retrieve($traceId);

list(): array

List all stored traces.

$traces = $storage->list();

purgeOldTraces(int $days): int

Remove traces older than specified days.

$deletedCount = $storage->purgeOldTraces(30);

PIIScrubber

Service for scrubbing sensitive data.

use Grazulex\LaravelChronotrace\Services\PIIScrubber;

$scrubber = app(PIIScrubber::class);

Methods

scrub(array $data): array

Scrub sensitive data from an array.

$cleanData = $scrubber->scrub([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'password' => 'secret123',
]);

// Result: ['name' => 'John Doe', 'email' => '[SCRUBBED]', 'password' => '[SCRUBBED]']

addPattern(string $pattern, string $replacement): void

Add a custom scrubbing pattern.

$scrubber->addPattern('/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/', '[CREDIT_CARD]');

Configuration API

Runtime Configuration

Get current configuration:

$config = config('chronotrace');

Check if enabled:

$enabled = config('chronotrace.enabled', false);

Modify configuration at runtime:

config(['chronotrace.mode' => 'always']);

Programmatic Usage Examples

Manual Trace Recording

use Grazulex\LaravelChronotrace\Services\TraceRecorder;

class OrderService
{
    public function processOrder(Order $order): void
    {
        $recorder = app(TraceRecorder::class);
        $recorder->startRecording();
        
        try {
            // Business logic
            $this->validateOrder($order);
            $this->chargePayment($order);
            $this->fulfillOrder($order);
            
            $traceId = $recorder->stopRecording();
            logger('Order processed successfully', ['trace_id' => $traceId]);
            
        } catch (Exception $e) {
            $traceId = $recorder->stopRecording();
            logger('Order processing failed', [
                'trace_id' => $traceId,
                'error' => $e->getMessage()
            ]);
            throw $e;
        }
    }
}

Custom Event Capture

use Grazulex\LaravelChronotrace\Services\TraceRecorder;

class PaymentService
{
    public function processPayment(Payment $payment): void
    {
        $recorder = app(TraceRecorder::class);
        
        if ($recorder->isRecording()) {
            $recorder->captureEvent('payment_started', [
                'payment_id' => $payment->id,
                'amount' => $payment->amount,
                'currency' => $payment->currency,
                'method' => $payment->method,
            ]);
        }
        
        // Process payment...
        
        if ($recorder->isRecording()) {
            $recorder->captureEvent('payment_completed', [
                'payment_id' => $payment->id,
                'status' => $payment->status,
                'transaction_id' => $payment->transaction_id,
            ]);
        }
    }
}

Conditional Recording

use Grazulex\LaravelChronotrace\Services\TraceRecorder;

class CriticalOperationService
{
    public function performCriticalOperation(): void
    {
        $recorder = app(TraceRecorder::class);
        
        // Start recording for critical operations only
        if ($this->isCriticalOperation()) {
            $recorder->startRecording();
        }
        
        // Perform operation...
        
        if ($recorder->isRecording()) {
            $traceId = $recorder->stopRecording();
            $this->notifyOpsTeam($traceId);
        }
    }
}

Middleware Integration

Custom Middleware

use Grazulex\LaravelChronotrace\Services\TraceRecorder;

class ConditionalTraceMiddleware
{
    public function handle($request, Closure $next)
    {
        $recorder = app(TraceRecorder::class);
        
        // Start recording based on custom conditions
        if ($this->shouldTrace($request)) {
            $recorder->startRecording();
        }
        
        $response = $next($request);
        
        if ($recorder->isRecording()) {
            $traceId = $recorder->stopRecording();
            $response->headers->set('X-Trace-ID', $traceId);
        }
        
        return $response;
    }
    
    private function shouldTrace($request): bool
    {
        // Custom logic to determine if request should be traced
        return $request->header('X-Debug-Trace') === 'true' ||
               $request->user()?->isAdmin() ||
               app()->environment('local');
    }
}

Event Listeners

Custom Event Listeners

use Grazulex\LaravelChronotrace\Services\TraceRecorder;

class CustomEventListener
{
    public function __construct(private TraceRecorder $recorder)
    {
    }

    public function handle(YourCustomEvent $event): void
    {
        if ($this->recorder->isRecording()) {
            $this->recorder->captureEvent('your_custom_event', [
                'event_type' => get_class($event),
                'event_data' => $event->getData(),
                'timestamp' => microtime(true),
            ]);
        }
    }
}

Register Custom Listeners

// In your EventServiceProvider
use Illuminate\Support\Facades\Event;

Event::listen(YourCustomEvent::class, CustomEventListener::class);

Advanced Usage

Trace Correlation

use Grazulex\LaravelChronotrace\Services\TraceRecorder;

class TraceCorrelationService
{
    public function correlateTraces(array $traceIds): array
    {
        $storage = app(TraceStorage::class);
        $correlatedData = [];
        
        foreach ($traceIds as $traceId) {
            $trace = $storage->retrieve($traceId);
            if ($trace) {
                $correlatedData[] = $this->extractCorrelationData($trace);
            }
        }
        
        return $this->analyzeCorrelation($correlatedData);
    }
}

Performance Monitoring

use Grazulex\LaravelChronotrace\Services\TraceRecorder;

class PerformanceMonitor
{
    public function monitor(callable $operation): mixed
    {
        $recorder = app(TraceRecorder::class);
        $startTime = microtime(true);
        $startMemory = memory_get_usage(true);
        
        $recorder->startRecording();
        
        try {
            $result = $operation();
            
            $endTime = microtime(true);
            $endMemory = memory_get_usage(true);
            
            $recorder->captureEvent('performance_metrics', [
                'execution_time' => $endTime - $startTime,
                'memory_usage' => $endMemory - $startMemory,
                'peak_memory' => memory_get_peak_usage(true),
            ]);
            
            return $result;
            
        } finally {
            $traceId = $recorder->stopRecording();
            logger('Performance trace completed', ['trace_id' => $traceId]);
        }
    }
}

Configuration Classes

Custom Storage Adapter

use Grazulex\LaravelChronotrace\Storage\TraceStorage;
use Grazulex\LaravelChronotrace\Models\TraceData;

class CustomStorageAdapter implements TraceStorage
{
    public function store(string $traceId, array $data): bool
    {
        // Implement custom storage logic
        return true;
    }
    
    public function retrieve(string $traceId): ?TraceData
    {
        // Implement retrieval logic
        return null;
    }
    
    public function list(): array
    {
        // Implement listing logic
        return [];
    }
    
    public function purgeOldTraces(int $days): int
    {
        // Implement cleanup logic
        return 0;
    }
}

Register Custom Storage

// In your service provider
$this->app->singleton(TraceStorage::class, CustomStorageAdapter::class);

Testing Support

Test Helpers

use Grazulex\LaravelChronotrace\Services\TraceRecorder;
use Illuminate\Foundation\Testing\TestCase;

class ChronoTraceTestCase extends TestCase
{
    protected function assertTraceRecorded(): void
    {
        $recorder = app(TraceRecorder::class);
        $this->assertTrue($recorder->isRecording());
    }
    
    protected function getLastTraceId(): ?string
    {
        $storage = app(TraceStorage::class);
        $traces = $storage->list();
        return $traces[0]['id'] ?? null;
    }
    
    protected function assertEventCaptured(string $eventType): void
    {
        $traceId = $this->getLastTraceId();
        $this->assertNotNull($traceId);
        
        $trace = app(TraceStorage::class)->retrieve($traceId);
        $events = $trace->getEvents();
        
        $this->assertTrue(
            collect($events)->contains('type', $eventType),
            "Event type '{$eventType}' was not captured"
        );
    }
}

Mock Storage for Testing

use Grazulex\LaravelChronotrace\Storage\TraceStorage;

class MockTraceStorage implements TraceStorage
{
    private array $traces = [];
    
    public function store(string $traceId, array $data): bool
    {
        $this->traces[$traceId] = $data;
        return true;
    }
    
    public function retrieve(string $traceId): ?TraceData
    {
        return $this->traces[$traceId] ?? null;
    }
    
    public function list(): array
    {
        return array_keys($this->traces);
    }
    
    public function purgeOldTraces(int $days): int
    {
        $this->traces = [];
        return count($this->traces);
    }
}

Next Steps

Clone this wiki locally