Photo by Luke Chesser on Unsplash

Improving Logging in Laravel with CorrelationID and TraceID

Daniel Archer
3 min readOct 17, 2023

--

Hello friends,

We’ve all been there: urgently debugging a project, only to find out that the logging is not as helpful as it should be. This can make a critical situation even worse. So today, I want to share some tips to improve your logging in Laravel. Let’s make life easier for ourselves down the line.

Better Messages and Data Context

Often, logs are cluttered with lines like:

Log::info('This is happening, '.$var.' was the result');

It’s good for a quick debug but lacks detailed information. Instead, use:

Log::info('Action happened', ['useful_var' => $var]);

Why is this better?

  1. Fixed Message: You can now use this as a metric, counting how many times this particular action occurred.
  2. Context Variables: Systems like Elasticsearch or Datadog can easily filter, search, or make operations based on these.
  3. Scalability: You can add more context without changing the original message, which keeps your log history clean and your dashboards intact.

Correlation ID (or requestID)

The Correlation ID is a powerful tool for improving your logs. When you have a flow that involves multiple steps or calls to different parts of your system, it’s challenging to know which logs are related to the same original request. By assigning a unique Correlation ID to each incoming request at the very start, you can pass this ID through all the different layers and services that handle the request. This makes it easy to aggregate all log entries that pertain to that specific request, giving you a holistic view for easier debugging and tracing.

How to set it up in Laravel?

Create a new middleware like this:

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Str;
use Closure;

class LoggingContextMiddleware
{
public function handle(Request $request, Closure $next): Response
{
Log::shareContext(array_filter([
'correlation_id' => Str::uuid()->toString(),
// Add more context here if needed
]));

return $next($request);
}
}

This middleware assigns a unique ID to every request, making it easier to trace logs. You can also add more context like user IDs, but let’s keep it simple for now.

TraceID

The TraceID takes logging to the next level, especially in systems that involve multiple services or microservices. While a Correlation ID helps you track logs within a single service, a TraceID helps you follow a request across different services. It becomes the thread that weaves through all your log data, making it possible to see the full journey of a request as it moves through various parts of your system. This is invaluable for debugging complex interactions between services and ensures that you have a complete picture of what’s happening.

Receiving a Request

When receiving a request, check if it contains a TraceID; if not, generate one:

// Inside your LoggingContextMiddleware
$traceID = $request->header('X-Trace-ID') ?? Str::uuid()->toString();

Sending a Request

When making a new request to another service, pass the TraceID along:

// Guzzle example
Http::withHeaders(['X-Trace-ID' => $traceID])->get('some-service-url');

Now you can track not just within a single service but across multiple services.

Conclusion

Using CorrelationID and TraceID changes the game for logging. These IDs make debugging easier and upgrade your monitoring dashboards. You can spot issues faster and understand user behavior more clearly.

This is just the beginning; adding more context to logs will become even easier in the future. Tracking requests helps you find bottlenecks and improve performance. It benefits both developers and users.

Trust me, making these changes today will make your future work much smoother. Hope this helps. Cheers! 🚀

--

--

Daniel Archer

Senior PHP Developer with 12+ years experience. Expert in high-availability systems, clean code, and best practices. Based in Dublin, Ireland.