If so how can it be done? By default L4 writes to a text file. I notice that Monolog can Log to Database on its github page.
5 Answers
Yep, You could create a listener to log everything in the routes.php
Event::listen('laravel.log', function($type,$message)
{
$log = new Log();
$log->message = $message;
$log->type = $type;
$log->update;
});
Or alternatively if you wanted to only log errors 400 and 500 Larvavel there is a Log event in the Routes.php file which listens to errors 404 and 500, you can write your own code in this event listener. So assuming you have a Model called Log defined,
Event::listen('404', function()
{
$error = "404: " . URL::full();
Log::error($error);
$update = new Log();
$update->error = $error;
$update->update;
return Response::error('404');
});
Event::listen('500', function()
{
Log::error($error);
$update = new Log();
$update->error = $error;
$update->update;
return Response::error('500');
});

- 375
- 2
- 7
As you can see if you read further the headline, Monolog natively supports writing to Redis, MongoDB and CouchDB. Those three are all supporting fairly write heavy (and very write heavy in the case of Redis) use-cases. MySQL is not there because logging to MySQL isn't really the best idea in the world.
If you really want to do it though, you can check the docs on creating your own handler, which explains how to create and use a PDO handler to write to a SQL database: https://github.com/Seldaek/monolog/blob/master/doc/extending.md - I still think it's a bad idea, but maybe the use case warrants it.

- 40,986
- 9
- 97
- 77
-
2Just to let you know, the code above will not actually work in L4 unless you specifically trigger the event using Event::fire(). In L4 you need to register the listener with the Log class rather than the Event class, eg: `Log::listen( function( $level, $message, $context ) { //code });` – JamesG Aug 22 '13 at 02:07
-
@PavelKostenko because if you have any kind of high load application you'll have a ton of MySQL writes which is not really what MySQL is best at compared to other specialized logging solutions. – Seldaek Aug 12 '15 at 15:23
For those who are wondering how to do it with laravel/lumen from 5.6 up to 7.x
- composer require wazaari/monolog-mysql
- Edit file config/logging.php as follows
<?php
use MySQLHandler\MySQLHandler;
...
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['daily', 'mysql'],
],
...
'mysql' => [
'driver' => 'monolog',
'level' => 'debug',
'handler' => MySQLHandler::class,
'with' => [
'pdo' => app('db')->connection()->getPdo(),
'table' => 'table-name',
],
]

- 2,617
- 2
- 18
- 25
In laravel 5 now it is illuminate.log
Now it will be like
Event::listen('illuminate.log', function($type,$message)
{
....
});

- 34,013
- 16
- 75
- 109