PHP code example of jftecnologia / laravel-tracing
1. Go to this page and download the library: Download jftecnologia/laravel-tracing library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
jftecnologia / laravel-tracing example snippets
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use JuniorFontenele\LaravelTracing\Middleware\IncomingTracingMiddleware;
use JuniorFontenele\LaravelTracing\Middleware\OutgoingTracingMiddleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
// Register tracing middleware to web group (for session-based correlation ID persistence)
$middleware->appendToGroup('web', IncomingTracingMiddleware::class);
$middleware->appendToGroup('web', OutgoingTracingMiddleware::class);
// Optional: Register to api group if you want tracing on API routes
// Note: API routes won't have session persistence, so correlation ID will be generated per request
$middleware->appendToGroup('api', IncomingTracingMiddleware::class);
$middleware->appendToGroup('api', OutgoingTracingMiddleware::class);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
// In routes/web.php
Route::middleware([
IncomingTracingMiddleware::class,
OutgoingTracingMiddleware::class,
])->group(function () {
Route::get('/traced', function () {
return response()->json(['status' => 'traced']);
});
});
use JuniorFontenele\LaravelTracing\Facades\LaravelTracing;
// Get correlation ID
$correlationId = LaravelTracing::correlationId();
// Get request ID
$requestId = LaravelTracing::requestId();
// Get all tracing values
$allTracings = LaravelTracing::all();
// Returns: ['correlation_id' => '...', 'request_id' => '...']
use Illuminate\Support\Facades\Log;
use JuniorFontenele\LaravelTracing\Facades\LaravelTracing;
Log::info('User action performed', LaravelTracing::all());
// Dispatch a job from a controller
dispatch(new ProcessOrder($orderId));
// Inside the job handler
class ProcessOrder implements ShouldQueue
{
public function handle(): void
{
// Access original correlation ID from the dispatching request
$correlationId = LaravelTracing::correlationId();
Log::info('Processing order', [
'correlation_id' => $correlationId, // Same as dispatching request
'request_id' => LaravelTracing::requestId(), // Preserved from dispatch
]);
}
}
use Illuminate\Support\Facades\Http;
// Attach all tracing headers to outgoing HTTP request
$response = Http::withTracing()
->get('https://api.example.com/data');
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use JuniorFontenele\LaravelTracing\Facades\LaravelTracing;
class OrderController extends Controller
{
public function store(Request $request)
{
// Get all tracing values
$tracings = LaravelTracing::all();
// Get specific values
$correlationId = LaravelTracing::correlationId();
$requestId = LaravelTracing::requestId();
// Use in business logic
$order = Order::create([
'user_id' => $request->user()->id,
'correlation_id' => $correlationId, // Store in database for audit
]);
return response()->json(['order_id' => $order->id]);
}
}
use Illuminate\Support\Facades\Log;
use JuniorFontenele\LaravelTracing\Facades\LaravelTracing;
// In any part of your application
Log::info('Processing payment', array_merge(
['amount' => 99.99, 'currency' => 'USD'],
LaravelTracing::all() // Add all tracing values to log context
));
// Dispatch job from controller
class OrderController extends Controller
{
public function store(Request $request)
{
$order = Order::create($request->all());
// Correlation ID and request ID are automatically serialized with the job
ProcessOrder::dispatch($order);
return response()->json(['order_id' => $order->id]);
}
}
// Job handler
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
use JuniorFontenele\LaravelTracing\Facades\LaravelTracing;
class ProcessOrder implements ShouldQueue
{
use Queueable;
public function __construct(public Order $order) {}
public function handle(): void
{
// Tracing values from the original request are restored
Log::info('Job processing order', [
'order_id' => $this->order->id,
'correlation_id' => LaravelTracing::correlationId(), // Same as dispatch request
'request_id' => LaravelTracing::requestId(), // Preserved from dispatch
]);
// Process order...
}
}
// Dispatch multiple jobs from the same request
public function bulkProcess(Request $request)
{
foreach ($request->orders as $order) {
ProcessOrder::dispatch($order);
SendInvoice::dispatch($order);
UpdateInventory::dispatch($order);
}
return response()->json(['status' => 'queued']);
}
use Illuminate\Support\Facades\Http;
// Call external service with tracing headers
public function fetchUserData(int $userId)
{
$response = Http::withTracing()
->get("https://api.example.com/users/{$userId}");
return $response->json();
}
// app/Tracings/UserIdSource.php
namespace App\Tracings;
use Illuminate\Http\Request;
use JuniorFontenele\LaravelTracing\Tracings\Contracts\TracingSource;
class UserIdSource implements TracingSource
{
public function resolve(Request $request): string
{
// Return authenticated user ID, or 'guest' if not authenticated
return (string) ($request->user()?->id ?? 'guest');
}
public function headerName(): string
{
return config('laravel-tracing.tracings.user_id.header', 'X-User-Id');
}
public function restoreFromJob(string $value): string
{
return $value; // No transformation needed
}
}
use JuniorFontenele\LaravelTracing\Facades\LaravelTracing;
// Access user ID from anywhere
$userId = LaravelTracing::get('user_id');
// Include in logs
Log::info('User action', [
'user_id' => LaravelTracing::get('user_id'),
'correlation_id' => LaravelTracing::correlationId(),
]);
// app/Providers/AppServiceProvider.php
use JuniorFontenele\LaravelTracing\Tracings\TracingManager;
use App\Tracings\UserIdSource;
public function boot(): void
{
app(TracingManager::class)->extend('user_id', new UserIdSource());
}
// Add to a controller to verify package is working
use JuniorFontenele\LaravelTracing\Facades\LaravelTracing;
dd(LaravelTracing::all());
// Should output: ['correlation_id' => '...', 'request_id' => '...']
// In job handler
use JuniorFontenele\LaravelTracing\Facades\LaravelTracing;
Log::info('Job tracings', LaravelTracing::all());
// Check logs to see if tracings are restored
// config/laravel-tracing.php
'tracings' => [
'user_id' => [
'enabled' => true, // Make sure this is true
'header' => 'X-User-Id',
'source' => \App\Tracings\UserIdSource::class,
],
],
// Check if tracing is registered
use JuniorFontenele\LaravelTracing\Facades\LaravelTracing;
dd(LaravelTracing::has('user_id')); // Should be true if registered