Laravel added a new Context
service to define contextual data to the current request. Context data is included in all log entries for that request, and queued jobs will also retain that same data. Using contextual data allows you to easily trace back code execution for a given request and any distributed flows in your application:
// In a middleware...
Context::add('hostname', gethostname());
Context::add('trace_id', (string) Str::uuid());
// In a controller...
Log::info('Retrieving commit messages for repository [{repository}].', [
'repository' => $repo,
]);
Http::get('https://github.com/...');
/*
Log entry example:
[2024-01-19 04:20:06] production.INFO: Retrieving commit messages for repository [laravel/framework]. {"repository":"laravel/framework"} {"hostname":"prod-web-1","trace_id":"a158c456-d277-4214-badd-0f4c8e84df79"}
*/
Contextual data also supports concepts like stacks, where you can push data to the same context, effectively appending data:
Event::listen(function (JobQueued $event) {
Context::push('queued_job_history', "Job queued: {$event->job->displayName()}");
});
Context::get('queued_job_history');
// [
// "Job queued: App\Jobs\MyFirstJob",
// "Job queued: App\Jobs\MySecondJob",
// "Job queued: App\Jobs\MyThirdJob",
// ]
If you'd like to learn more about this feature, check out the Pull Request description. Hat tip to Tim MacDonald, who created this feature for the framework!
The post Introducing the Context Facade in Laravel appeared first on Laravel News.
Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.