6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravelライブラリ探訪 - SQL実行ログを取るのに便利なライブラリ - Laravel SQL Logger

Last updated at Posted at 2018-07-09

Laravel開発でのSQLログを取る

LaravelでSQL実行ログを取るには、 \DB::listenのリスナーを自前で登録してログを取る等が可能であるが、容易にライブラリで実現出来る物があるので紹介
※ Laravel5.6、ライブラリのバージョンはv2.0.3で確認

mnabialek/laravel-sql-logger

導入方法

ReadMeの通り、ライブラリのインストールと設定ファイルの配置を行う

composer require mnabialek/laravel-sql-logger --dev
php artisan vendor:publish --provider="Mnabialek\LaravelSqlLogger\Providers\ServiceProvider"

.envに以下を追加し必要に応じて調整

SQL_LOGGER_DIRECTORY="logs/sql"
SQL_LOGGER_USE_SECONDS=false
SQL_LOGGER_CONSOLE_SUFFIX=
SQL_LOGGER_LOG_EXTENSION=".sql"
SQL_LOGGER_ALL_QUERIES_ENABLED=true
SQL_LOGGER_ALL_QUERIES_OVERRIDE=false
SQL_LOGGER_ALL_QUERIES_PATTERN="#.*#i"
SQL_LOGGER_ALL_QUERIES_FILE_NAME="[Y-m-d]-log"
SQL_LOGGER_SLOW_QUERIES_ENABLED=true
SQL_LOGGER_SLOW_QUERIES_MIN_EXEC_TIME=100
SQL_LOGGER_SLOW_QUERIES_PATTERN="#.*#i"
SQL_LOGGER_SLOW_QUERIES_FILE_NAME="[Y-m-d]-slow-log"

これで、デフォルトだとstorage/logs/sqlフォルダ以下に日別でSQL実行結果のログをプレースホルダの変数を適用済みで出力してくれる。
必要に応じてスロークエリも出力できるのでシステム開発を効率的に行うことが可能

SQL実行ログの例

/* Origin (request): GET http://xxx.example.com/posts/1
   Query 2 - 2018-07-09 12:00:00 [0.45ms] */
select * from `posts` where `id` = 5 and `posts`.`deleted_at` is null limit 1;
6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?