以 Laravel5 为示例!
一、添加一个日志通道 : 打开 config/logging.php
'sql' =>[ <span class="hljs-string"> 'driver' </span> =&gt; <span class="hljs-string"> 'daily' </span> , <span class="hljs-string"> 'level' </span> =&gt; <span class="hljs-string"> 'debug' </span> , <span class="hljs-string"> 'path' </span> =&gt; storage_path( <span class="hljs-string"> 'logs/sql/log.log' </span> ),
],
</code> </pre>
二、创建监听器
php artisan make:listener QueryListener -- event =Illuminate\Database\Events\QueryExecuted
1、打开 app/Providers/EventServiceProvider.php ,在 $listen 中添加:
protected $listen = [ 'Illuminate\Database\Events\QueryExecuted' => [ 'App\Listeners\QueryListener', ] ];
2、打开 app/Listeners/QueryListener 文件:
//第一步:头部引入log use Illuminate\Support\Facades\Log; //第二步:handle方法修改如下 public function handle(QueryExecuted $event) { if (env('APP_DEBUG') { $sql = str_replace("?", "'%s'", $event-\>sql); $log = vsprintf($sql, $event-\>bindings); $logDir = storage_path('logs/sql'); if (!is_dir($logDir)) { mkdir($logDir, 0777, true); } Log::channel('sql')-&gt;info($log); } } </code> </pre> 三、测试Laravel记录SQL日志是否成功? ----------------------- 运行代码,就可以在 storage/logs/sql 下 看到sql 日志了!