Laravel 记录SQL日志

来源:互联网 发布:cntv for mac 编辑:程序博客网 时间:2024/05/19 23:10

在项目开发过程中或者是性能优化中,经常会有要查看执行sql的情况,然而Laravel日志默认不记录执行sql。好在留有相关接口,我们可以很方便的就是想SQl日志功能。

  1. 在 App\Providers\EventServiceProvider:class 中的$listen中新增如下
protected $listen = [    'App\Events\Event' => [        'App\Listeners\EventListener',    ],    // 新增SqlListener监听QueryExecuted    'Illuminate\Database\Events\QueryExecuted' => [        'App\Listeners\SqlListener',    ],];
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  1. 新建SqlListener监听器

方法1,手动创建,在App\Listeners\SqlListener.PHP 文件,内容如下

namespace App\Listeners;use Illuminate\Database\Events\QueryExecuted;class SqlListener {    /**     * Create the event listener.     *     * @return void     */    public function __construct() {        //    }    /**     * Handle the event.     *     * @param  =QueryExecuted  $event     * @return void     */    public function handle(QueryExecuted $event) {        // 在这里编写业务逻辑    }}
  • 1

方法2,使用命令行创建,命令如下

// 该命令必须在项目跟目录下执行,因为项目跟目录下才有artisan文件。// 该命令可以自动创建SqlListener文件,但是QueryExecuted这个类的导入可能会有点问题,自己改下。> php artisan make:listener SqlListener -e=QueryExecuted
  • 1
  1. 在handle方法中编写记录sql的业务逻辑,如:
/** * 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 = '[' . date('Y-m-d H:i:s') . '] ' . $log . "\r\n";    $filepath = storage_path('logs\sql.log');    file_put_contents($filepath, $log, FILE_APPEND);    // 这里也可以直接用Log::info() 里的函数,只是这样会和其他调试信息掺在一起。    // 如果要用Log里的函数,别忘记了引入Log类。}