Putting unique id to requests one of my silver bullet while designing RESTful APIs. It provides an extremely easy way to follow each request’s lifecycle while debugging. In this guide I’ll show you how you can add it to your log files on Laravel 5.6.

Under the hood, Laravel utilizes the Monolog library, which provides support for a variety of powerful log handlers. Laravel makes it a cinch to configure these handlers, allowing you to mix and match them to customize your application’s log handling.

Define a tap array on the channel's configuration

The tap array should contain a list of classes that should have an opportunity to customize (or "tap" into) the Monolog instance after it is created. (In this example we created LocalLogger)

Create a new Log Handler

This class only needs a single method: __invoke , which receives an Illuminate\Log\Logger instance. The Illuminate\Log\Logger instance proxies all method calls to the underlying Monolog instance:

Because of uniqeid() is not actually unique and deprecated soon. bin2hex(random_bytes(16)) functions are good replacement for that kind of scenarios.

You can always add Request Method, Route, Client’s IP any kind of informational data on your new LocalLogger class. It's just an example.

Usage Examples

Let's create a new middleware php artisan make:middleware LogRequestResponse and assign it to api groups at /app/Http/Kernel.php

2. Create a dummy Route at routes/api.php:

3. Open your log file:

[2018-06-26 07:51:54] b8be25da3126dcaad75961ae38dc7c0e local.INFO: app.request {"request":[],"header":{"accept-language":["en-US,en;q=0.9,tr;q=0.8,la;q=0.7"],"accept-encoding":["gzip, deflate"],"accept":["*/*"],"postman-token":["69d48b67-7c5d-c783-71fc-2e5e266da45c"],"user-agent":["Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36"],"cache-control":["no-cache"],"connection":["keep-alive"],"host":["ifpay.test"],"content-length":[""],"content-type":[""]}} [2018-06-26 07:51:54] b8be25da3126dcaad75961ae38dc7c0e local.INFO: I am just a info error. [2018-06-26 07:51:54] b8be25da3126dcaad75961ae38dc7c0e local.CRITICAL: I am a critical error [2018-06-26 07:51:54] b8be25da3126dcaad75961ae38dc7c0e local.INFO: app.response {"response":"","header":{"cache-control":["no-cache, private"],"date":["Tue, 26 Jun 2018 07:51:54 GMT"],"x-ratelimit-limit":[60],"x-ratelimit-remaining":[57]}}

You'll see the unique id: b8be25da3126dcaad75961ae38dc7c0e and you can easily follows what's going on in this request with tailing log file like this:

cat storage/logs/laravel-2018–06–26.log | grep 0c67aef34c9a1b4f5f165926336e96a0

If you have any question you can always ping me at Twitter! Good luck with the logging stuff!