正文  电脑教程 > 服务器教程 >

Laravel如何给生产环境添加监听事件

本文主要给大家介绍的是关于Laravel给生产环境添加监听事件(SQL日志监听)的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍: ...

本文主要给大家介绍的是关于Laravel给生产环境添加监听事件(SQL日志监听)的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍:

laravel版本:5.2.*

一、创建监听器

php artisan make:listener QueryListener --event=Illuminate\Database\Events\QueryExecuted

or

sudo /usr/local/bin/php artisan make:listener QueryListener --event=Illuminate\Database\Events\QueryExecuted

会自动生成文件 app/Listeners/QueryListener.php

二、注册事件

打开 app/Providers/EventServiceProvider.php,在 $listen 中添加 IlluminateDatabaseEventsQueryExecuted 事件的监听器为 QueryListener

protected $listen = [ 
 ‘IlluminateDatabaseEventsQueryExecuted‘ => [
  ‘AppListenersQueryListener‘,
 ],
];

最终代码如下

namespace AppProviders;
use IlluminateContractsEventsDispatcher as DispatcherContract;
use IlluminateFoundationSupportProvidersEventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
 /**
  * The event listener mappings for the application.
  *
  * @var array
  */
 protected $listen = [
  ‘AppEventsSomeEvent‘ => [
   ‘AppListenersEventListener‘,
  ],
  ‘IlluminateDatabaseEventsQueryExecuted‘ => [
   ‘AppListenersQueryListener‘,
  ],
 ];
 /**
  * Register any other events for your application.
  *
  * @param IlluminateContractsEventsDispatcher $events
  * @return void
  */
 public function boot(DispatcherContract $events)
 {
  parent::boot($events);
  //
 }
}

三、添加逻辑

打开 app/Listeners/QueryListener.php

光有一个空的监听器是不够的,我们需要自己实现如何把 $sql 记录到日志中。为此,对 QueryListener 进行改造,完善其 handle 方法如下:

$sql = str_replace("?", "‘%s‘", $event->sql);
$log = vsprintf($sql, $event->bindings);
Log::info($log);

最终代码如下

namespace AppListeners;
use Log;
use IlluminateDatabaseEventsQueryExecuted;
use IlluminateQueueInteractsWithQueue;
use IlluminateContractsQueueShouldQueue;
class QueryListener
{
 /**
  * Create the event listener.
  *
  * @return void
  */
 public function __construct()
 {
  //
 }
 /**
  * Handle the event.
  *
  * @param QueryExecuted $event
  * @return void
  */
 public function handle(QueryExecuted $event)
 {
  $sql = str_replace("?", "‘%s‘", $event->sql);
  $log = vsprintf($sql, $event->bindings);
  Log::info($log);
 }
}