Automatically tag logs on Telescope
September 16, 2020 by Wouter Peschier
laravel telescopeI often find myself getting lost in the number of logs on Telescope. This little trick will allow you to automatically tag logs so it's easier to filter specific logs.
Telescope has a tag
function that allows you to filter incoming requests by type. In this case we want to filter log requests and tag them with a tag specified in the log message itself.
Lets have a look at an example log message:
logger()->info('[stripe] Payment received');
In this case we want any log message that starts with [stripe]
to get tagged automatically. To do this add the following to the TelescopeServiceProvider.php
file:
// app/Providers/TelescopeServiceProvider.php
use Laravel\Telescope\Telescope;
public function register()
{
$this->hideSensitiveRequestDetails();
Telescope::tag(function (IncomingEntry $entry) {
if ($entry->type === 'log') {
$message = $entry->content['message'];
// Check if the log message starts with a square bracket
if (strpos($message, '[') === 0) {
// Extract the tag that's inside the square brackets
preg_match('/\[(.*?)\]/', $message, $tag);
return [$tag[1]];
}
}
return [];
});
}
What we are doing above is first checking if the log message starts with a square bracket, if it doesn't we can skip it as it's a normal log without a tag. If it does start with a square bracket we use a regular expression to extract the tag from inside the square brackets and add it to the Telescope log entry.
If you check your log entry on Telescope you will see that the stripe
tag has been automatically applied and you can click on it to filter logs with just that tag. This can be very useful if you have a few processes writing to the log but you are only interested in one specific part.