Can Laravel 4 log to a MySQL database?

Nyxynyx picture Nyxynyx · Mar 23, 2013 · Viewed 7.9k times · Source

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.

Answer

Pratheek Rebala picture Pratheek Rebala · Mar 25, 2013

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');
});