Using Laravel 11’s Context

Screenshot 2024-04-10 at 17.12.04

Introduced in Laravel 11, the “context” features offer an innovative way to capture, retrieve, and share information across requests, jobs, and commands within your applications. This functionality not only enriches the logging process with valuable metadata but also ensures the seamless flow of information, especially in distributed system setups.

 

Quick Overview on How It Works

To harness Laravel’s context capabilities, developers can utilize the Context facade or the context() helper function to add relevant information, such as a request URL and a unique trace ID. The context is typically added through middleware at the beginning of every incoming request. This context is not only automatically appended as metadata to any log entries made during the request but is also preserved and applied when handling queue jobs.

 

Practical Examples of Leveraging Context

 

Enhancing Job Traceability

One of the standout features of Laravel’s context capabilities is the maintenance of context information within queued jobs. This proves invaluable for tracing back the origin of a job to a specific request, aiding in debugging and monitoring.

When a request to export customer data is received, the relevant context is captured as follows:

This context is used when logging within the `ExportCustomers` job, ensuring that each step of the process is traceable back to the original request:

The resulting log entry provides a comprehensive overview of the export action, enriched with the context of the original request:

Customer data export. {“details”:{…}} {“tracking_id”:”123e4567-e89b-12d3-a456-426614174000″, “request_url”:”https://example.com/export“}

Using a unique tracking_id and request_url, organizations can make data exports fully traceable and securely linked to their origin, improving transparency and accountability.

 

Tracking Historical Information with Stacks

Context stacks facilitate tracking sequences of events or historical data throughout the lifecycle of a request. A great example is to capture query durations.

This is great for capturing and reviewing the sequence of database queries executed during a request lifecycle, providing deeper insights into the application’s behaviour and performance. In addition, this logs queries only for requests that exceed the 5-second threshold:

 

Conclusion

With the introduction of context capabilities in Laravel 11, developers are equipped with powerful tools for enhancing application traceability, debugging, and information sharing. By integrating context into your Laravel projects, you can achieve a higher level of insight into your application’s flow and behaviour, making your development process more efficient and your application more robust and maintainable.

 

Related blogs

Want to get in touch and learn more about what we can do? We love to just have a chat digital or in person.