laravel添加sql监听
程序员文章站
2022-06-14 13:37:31
...
laravel添加sql监听
- 添加listener文件
php artisan make:listener QueryListener
- 在listener文件中添加执行函数
<?php
namespace App\Listeners;
use Illuminate\Database\Events\QueryExecuted;
class QueryListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param QueryExecuted $event
* @return void
*/
public function handle(QueryExecuted $event)
{
try{
if (env('APP_DEBUG') == true) { // 如果需要调试
$sql = str_replace("?", "'%s'", $event->sql);
foreach ($event->bindings as $i => $binding) {
if ($binding instanceof \DateTime) {
$event->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
} else {
if (is_string($binding)) {
$event->bindings[$i] = "'$binding'";
}
}
}
$log = vsprintf($sql, $event->bindings);
$log = $log.' [ RunTime:'.$event->time.'ms ] ';
$logger = fileLogger('sql', 'sql');
$logger->info($log); // 将sql语句打印到log中
}
}catch (\Exception $e){
\Log::error('log sql error:'.$e->getMessage());
}
}
}
- 在
App\Providers\EventServiceProvider
中添加listen
<?php
namespace App\Providers;
use App\Listeners\QueryListener;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
QueryExecuted::class => [
QueryListener::class,
]
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
//
}
}
- 配置完成,之后只要设置
APP_DEBUG = true
就可以打印sql语句到log中了