ablog

不器用で落着きのない技術者のメモ

Aurora Postgres で実行したクエリをログに出力する

設定

  • DB パラメータグループを作成して以下の通り設定する
    • log_statement:all
    • log_min_duration_statement: 1
    • log_destination: csvlog
  • DBインスタンスに作成したパラメータグループを設定する

設定確認

  • AWSマネジメントコンソールで確認できるが、接続しているセッションで以下の通り確認できる。
% psql "host=aurora-postgres-r42xl.*********.ap-northeast-1.rds.amazonaws.com user=****** dbname=mydb port=5432"
Password:
Timing is on.
psql (9.6.2, server 9.6.6)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
Type "help" for help.

aurora-postgres-r42xl awsuser 07:06 => show log_statement;
 log_statement
---------------
 all
(1 row)

Time: 14.281 ms
aurora-postgres-r42xl awsuser 07:06 => show log_min_duration_statement;
 log_min_duration_statement
----------------------------
 1ms
(1 row)

Time: 13.284 ms

クエリを確認する

  • AWSマネジメントコンソールから error/postgresql.log.*.csv を確認する。

参考

DB インスタンスに関連付けられている DB パラメータグループの 2 つパラメーター log_statement と log_min_duration_statement を設定することで、PostgreSQL DB インスタンスのクエリログ記録を有効にすることができます。log_statement パラメーターでは、どの SQL ステートメントをログに記録するかを制御します。このパラメーターを all に設定して、すべてのステートメントがログに記録されるようにすることをお勧めします。デフォルト値は none です。または、この値を ddl に設定して、すべてのデータ定義言語 (DDL) ステートメント (CREATE、ALTER、DROP など) がログに記録されるようにすることもできます。さらに、mod に設定して、すべての DDL とデータ変更言語 (DML) ステートメント (INSERT、UPDATE、DELETE) がログに記録されるようにすることもできます。

log_min_duration_statement パラメーターでは、ログに記録するステートメントの制限をミリ秒単位で設定します。このパラメーターで設定した時間より長く実行されたすべての SQL ステートメントがログに記録されます。このパラメーターはデフォルトでは無効になっており、マイナス 1 (-1) に設定されています。このパラメーターを有効にすると、最適化されていないクエリを見つけるために役立ちます。これらの設定の詳細については、PostgreSQL のドキュメントの「エラー報告とログ記録」を参照してください。

PostgreSQL データベースのログファイル - Amazon Relational Database Service

log_statement (enum)
Controls which SQL statements are logged. Valid values are none (off), ddl, mod, and all (all statements). ddl logs all data definition statements, such as CREATE, ALTER, and DROP statements. mod logs all ddl statements, plus data-modifying statements such as INSERT, UPDATE, DELETE, TRUNCATE, and COPY FROM. PREPARE, EXECUTE, and EXPLAIN ANALYZE statements are also logged if their contained command is of an appropriate type. For clients using extended query protocol, logging occurs when an Execute message is received, and values of the Bind parameters are included (with any embedded single-quote marks doubled).

https://www.postgresql.org/docs/9.6/static/runtime-config-logging.html

log_min_duration_statement (integer)
Causes the duration of each completed statement to be logged if the statement ran for at least the specified number of milliseconds. Setting this to zero prints all statement durations. Minus-one (the default) disables logging statement durations. For example, if you set it to 250ms then all SQL statements that run 250ms or longer will be logged. Enabling this parameter can be helpful in tracking down unoptimized queries in your applications. Only superusers can change this setting.

https://www.postgresql.org/docs/9.6/static/runtime-config-logging.html