14
21

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.

PHPのPDOをpdo-debugを使ってSQLロギングしてみる

Last updated at Posted at 2015-08-18

最近のフレームワークなどではSQLロギングなんて当たり前だと思いますが、古いシステムなどではまだPDO直で書いてます!!!だったり、パフォーマンスのためPDO直で書いてます!!!とかそういう環境もあるとおもいます。
そんな直PDOをロギングするときに便利なpdo-debugを使ったときのメモ

環境

* PHP 5.6

参考にしたサイト

composer経由でインストールする

panique/pdo-debugのREADMEをそのままやればいいです。

composer.json
"require-dev": {
    "panique/pdo-debug": "0.2"
}

でインストール

composer install

使い方

READMEそのまんまでOKかと

$parameters = array(
    'param1' => 'hello',
    'param2' => 123,
    'param3' => null
);
$sql = "INSERT INTO test (col1, col2, col3) VALUES (:param1, :param2, :param3)";
$query = $database_connection->prepare($sql);
$query->execute($parameters);
# プレースホルダの中身がパースされてSQLが出力される
echo PdoDebugger::show($sql, $parameters);

これに加えて実行時間でも足したらクエリの発行時間とかわかっていいのかと

$parameters = array(
    'param1' => 'hello',
    'param2' => 123,
    'param3' => null
);
$sql = "INSERT INTO test (col1, col2, col3) VALUES (:param1, :param2, :param3)";
# 計測スタート
$time_start = microtime(true);
$query = $database_connection->prepare($sql);
$query->execute($parameters);
# 計測 終了
$time_end = microtime(true);

# プレースホルダの中身がパースされてSQLが出力される
$debug = array(
	'time' => $time_end - $time_start,
	'sql'  => PdoDebugger::show($sql, $parameters)
);
# ログでも吐いてみたらいかがでしょう
error_log(json_encode($debug), 3, "/var/tmp/my-errors.log");

jsonでログを吐けばjqで綺麗に整形してくれるので便利

tail -f /var/tmp/my-errors.log | jq .

簡単なSQLプロファイラの出来上がりです。

14
21
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
14
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?