Laravel 4可以登录MySQL数据库吗?

Nyx*_*nyx 10 php laravel monolog laravel-4

如果是这样,怎么办呢?默认情况下,L4写入文本文件.我注意到Monolog可以在其github页面上登录数据库.

小智 10

是的,你可以创建一个监听器来记录routes.php中的所有内容

Event::listen('laravel.log', function($type,$message)
{
    $log = new Log();
    $log->message = $message;
    $log->type = $type;
    $log->update;
});
Run Code Online (Sandbox Code Playgroud)

或者,如果您只想记录错误400和500 Larvavel,在Routes.php文件中有一个侦听错误404和500的Log事件,您可以在此事件侦听器中编写自己的代码.假设您有一个名为Log的模型,

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');
});
Run Code Online (Sandbox Code Playgroud)


Sel*_*aek 7

正如您所看到的,如果您进一步阅读标题,Monolog本身支持写入Redis,MongoDB和CouchDB.这三个都支持相当重写(在Redis的情况下非常重写)用例.MySQL不在那里,因为登录到MySQL并不是世界上最好的主意.

如果你真的想这样做,你可以检查创建自己的处理程序的文档,这解释了如何创建和使用PDO处理程序写入SQL数据库:https://github.com/Seldaek/monolog/blob /master/doc/extending.md - 我仍然认为这是一个坏主意,但也许用例保证它.

  • 只是为了让您知道,除非您使用Event :: fire()专门触发事件,否则上述代码在L4中实际上不起作用.在L4中,您需要使用Log类而不是Event类注册侦听器,例如:`Log :: listen(function($ level,$ message,$ context){// code}); (2认同)