利用监听器进行sql语句记录
1、监听sql语句的事件类已经定义,直接创建监听器类即可:
# 监听sqlmake:listener QueryListener --event=Illuminate\Database\Events\QueryExecuted
2、监听器类代码
./app/Listeners/QueryListener.php
<?phpnamespace App\Listeners;use Illuminate\Database\Events\QueryExecuted;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Contracts\Queue\ShouldQueue;use App\Http\Models\OperationLog;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 = vsprintf(str_replace("?", "'%s'", $event->sql), $event->bindings) . " \t[" . $event->time . ' ms] ';Log::error($sql);}}
3、引入监听器
./app/Providers/EventServiceProvider.php
protected $listen = [...\Illuminate\Database\Events\QueryExecuted::class => ['App\Listeners\QueryListener'],...];
此时进行操作时就会记录sql日志
相关文章:
Lumen 框架sql监听
1、创建sql监听器
QueryListener.php
<?phpnamespace App\Listeners;use App\Http\Helpers\FunctionHelper;use Illuminate\Database\Events\QueryExecuted;use Illuminate\Support\Facades\Log;class QueryListener{/*** Create the event listener.** @return void*/public function __construct(){//}/*** Handle the event.** @param QueryExecuted $event* @return void*/public function handle(QueryExecuted $event){if (FunctionHelper::isTestEnv()) {Log::info($event->sql);Log::info($event->bindings);}}}
2、加入到监听服务中
EventServiceProvider.php
<?phpnamespace App\Providers;use App\Listeners\QueryListener;use Illuminate\Database\Events\QueryExecuted;use Laravel\Lumen\Providers\EventServiceProvider as ServiceProvider;class EventServiceProvider extends ServiceProvider{/*** The event listener mappings for the application.** @var array*/protected $listen = [\App\Events\ExampleEvent::class => [\App\Listeners\ExampleListener::class,],# 注册sql监听QueryExecuted::class => [QueryListener::class,],];}
3、项目入口引入监听服务
bootstrap/app.php
$app->register(App\Providers\EventServiceProvider::class);
