{"id":269,"title":"laravel\u76d1\u542csql\u5e76\u751f\u6210\u65e5\u5fd7,php artisan make:listener","good":0,"bad":0,"hit":2970,"created_at":"2017-10-20 11:06:29","content":"
\u9879\u76ee\u6839\u76ee\u5f55\u4e0b\u6267\u884c\uff1a<\/p>
php artisan make:listener SqlListener -e=QueryExecuted<\/p>
\u4f1a\u5728App\\Listener\\\u4e0b\u751f\u6210\u4e00\u4e2aSqlListener\u6587\u4ef6\uff0c\u4fee\u6539\u4ee3\u7801\uff1a<\/p>
<?php \u7136\u540e\u5728App\/Provider\/EventServiceProvider.php\u4e2d\u52a0\u5165\uff1a <?php \u7ed9sql.log\u5199\u5165\u6743\u9650\uff0c\u6267\u884c\u76f8\u5e94\u7a0b\u5e8f\u4f1a\u81ea\u52a8\u8bb0\u5f55sql,\u4e5f\u53ef\u4ee5\u7528tailf\u8ddf\u8e2a\uff0c\u4e0d\u8fc7\u8981\u6ce8\u610f\u5b89\u5168\uff0c\u8fd9\u4e2a\u653e\u7f51\u4e0a\u53ef\u80fd\u4f1a\u66b4\u9732\u6570\u636e\u5e93\u7ed3\u6784<\/p>"}
namespace App\\Listeners;
use Illuminate\\Database\\Events\\QueryExecuted;
use Illuminate\\Queue\\InteractsWithQueue;
use Illuminate\\Contracts\\Queue\\ShouldQueue;
class SqlListener
{
\/**
* 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 .= "\\r\\n-----------------------------------------------";
$log = $log . "\\r\\n";
$filePath = storage_path('logs\/sql.log');<\/strong>
file_put_contents($filePath, $log, FILE_APPEND);
}
}
<\/p>
<\/p>
<\/p>
namespace App\\Providers;
use Illuminate\\Support\\Facades\\Event;
use Illuminate\\Foundation\\Support\\Providers\\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
\/**
* The event listener mappings for the application.
*
* @var array
*\/
protected $listen = [
'App\\Events\\SomeEvent' => [
'App\\Listeners\\EventListener',
],
'Illuminate\\Database\\Events\\QueryExecuted' => [
'App\\Listeners\\SqlListener'
]<\/strong>
];
\/**
* Register any events for your application.
*
* @return void
*\/
public function boot()
{
parent::boot();
\/\/
}
}
<\/p>
<\/p>
<\/p>