概要
Query Builderが内部で生成しているSQLをログに出力する方法。
方法
Query Builderを呼び出している箇所で以下のコードを追加する。
public function findAccountEntityByEmail(EmailValue $emailValue): AccountEntity
{
$selectColumns = [
'a.id',
'a.status',
'a.lock_version AS accounts_lock_version',
'ae.id AS email_id',
'ae.email',
'ae.email_verified',
'ae.lock_version AS accounts_emails_lock_version',
'ap.id AS password_id',
'ap.password_hash',
'ap.lock_version AS accounts_passwords_lock_version',
];
// SQLを実行する前にこれを追加する
\DB::enableQueryLog();
$account = \DB::table('accounts_emails AS ae')
->select($selectColumns)
->join('accounts AS a', 'a.id', '=', 'ae.account_id')
->join('accounts_passwords AS ap', 'a.id', '=', 'ap.account_id')
->where('ae.email', '=', $emailValue->getEmail())
->first();
// ロギングクラスを使ってログに出力する
// "sql_debug_log", "findAccountEntityByEmail"の部分には任意の名前を入れられる
\Log::debug(
'sql_debug_log',
[
'findAccountEntityByEmail' => \DB::getQueryLog()
]
);
デフォルトだと、storage/logs/laravel.log に出力されているハズなので確認します。
↓1行で出力しているので少し見にくいですが以下のように出力されます。
laravel.log
[2016-11-27 08:11:57] testing.DEBUG: sql_debug_log {"findAccountEntityByEmail":[{"query":"select `a`.`id`, `a`.`status`, `a`.`lock_version` as `accounts_lock_version`, `ae`.`id` as `email_id`, `ae`.`email`, `ae`.`email_verified`, `ae`.`lock_version` as `accounts_emails_lock_version`, `ap`.`id` as `password_id`, `ap`.`password_hash`, `ap`.`lock_version` as `accounts_passwords_lock_version` from `accounts_emails` as `ae` inner join `accounts` as `a` on `a`.`id` = `ae`.`account_id` inner join `accounts_passwords` as `ap` on `a`.`id` = `ap`.`account_id` where `ae`.`email` = ? limit 1","bindings":["account-create-test-success-required-params@gmail.com"],"time":1.1}]}