Reputation: 282805
How can I override how Laravel/Monolog formats Exceptions?
Right now they're coming out like this:
Next exception 'Illuminate\Database\QueryException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pay.booking_id' in 'where clause' (SQL: select `seg`.`id` as `segment_id`, ..*snip*.. in /srv/myproject/vendor/laravel/framework/src/Illuminate/Database/Connection.php:729
Stack trace:
#0 /srv/myproject/vendor/laravel/framework/src/Illuminate/Database/Connection.php(685): Illuminate\Database\Connection->runQueryCallback('select `seg`.`i...', Array, Object(Closure))
#1 /srv/myproject/vendor/laravel/framework/src/Illuminate/Database/Connection.php(349): Illuminate\Database\Connection->run('select `seg`.`i...', Array, Object(Closure))
#2 /srv/myproject/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(1610): Illuminate\Database\Connection->select('select `seg`.`i...', Array, true)
#3 /srv/myproject/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(1596): Illuminate\Database\Query\Builder->runSelect()
I want to take the Exception object and format it myself (return a string). I do not want to override/reimplement where the logs go (what file) or anything of that nature.
Using Laravel 5.2.
Upvotes: 1
Views: 3365
Reputation: 8750
I am not sure if this is what you are looking for, but you could extend the LogManager class and replace the Formatter with your own.
I created a new LogManager
which is as follows:
<?php
namespace App\Support\Log;
use Illuminate\Log\LogManager as BaseLogManager;
use Monolog\Formatter\LineFormatter;
class LogManager extends BaseLogManager
{
protected function formatter()
{
$format = "%channel%.%level_name%: %message% %context% %extra% [%datetime%]\n";
return tap(new LineFormatter($format, null, true, true), function ($formatter) {
$formatter->includeStacktraces();
});
}
}
.. which extends Laravel's base Log Manager, but with an overriden formatter()
.
You will also notice the format of the message is changed whereby the date is appended to the last part of the string.
The only thing left to do was to bind this into the container rather than the default one. So, in my AppServiceProvider@register()
, I added this:
use App\Support\Log\LogManager;
$this->app->singleton('log', function () {
return new LogManager($this->app);
});
.. and sure enough, the new log format is as such:
local.INFO: test [2019-01-14 04:42:07]
You could also take a look at the LineFormatter class and see what other things you could possibly do with it.
Is this what you are looking for?
Upvotes: 2