LoginSignup
1
1
記事投稿キャンペーン 「2024年!初アウトプットをしよう」

DockerのMySQLで実行したSQLをログ出力させる

Last updated at Posted at 2024-01-25

DockerのMySQL(mysql5.7.26)で、実行したSQLをログ出力させることに少々苦戦したので方法を共有します。
どれだけ需要があるか分からないですが一応。。

先に結論

my.cnfに以下を追加して、mysqlを再起動する。

[mysqld]
general_log=1
general_log_file=/var/log/mysql/myquery.log

自分の環境のmy.cnfは以下のようになりました。

# Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/

[mysqld]
general_log=1
general_log_file=/var/log/mysql/myquery.log

いくつかハマったポイントがあったので、それも記載しておきます。

ハマりポイント1:my.cnfの場所

ネットで「mysql sqlログ出力」と検索したら/etc/my.cnfにログ出力するように追記すると書かれていたので

ls -l /etc/my.cnf

とやったところ、そんなファイル無いと怒られました。。
なのでfindで探してみたら複数出てきたのでどれ??となり、

find -name my.cnf
./var/lib/dpkg/alternatives/my.cnf
./etc/alternatives/my.cnf
./etc/mysql/my.cnf

さらに検索したところ、以下の記事が見つかりました。
MySQLで読み込まれる設定(my.cnf)の場所はどこ?
書かれているコマンドを実行した結果がこちら。

mysql --help | grep my.cnf
order of preference, my.cnf, $MYSQL_TCP_PORT,
/etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf 

ということで、今回の環境だと/etc/mysql/my.cnfを見ていることが分かりました。

ハマりポイント2:コンテナ内にvimがない(viもなかった)

マジか!?と思いつつインストールしたらエラーになり入れられず。。

apt install vi
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package vi

これを解決するのは面倒そう&本筋じゃないということで、ローカル環境で必要部分を追記したmy.cnfを作成して、コンテナにコピーしました。

docker cp ./my.cnf local-db-1:/etc/mysql/mysql.cnf
docker restart local-db-1

ハマりポイント3:追記する文字列の正解が不明

ネットで検索した記事だと、ログ出力の定義を追記するグループが[mysqld][mysql]派が混在していたり、general-log=1(ハイフン)とgeneral_log=1(アンダーバー)派が混在していたりで何が正しいのかがよく分からなかったです。
とりあえず一つ一つ試してみるという原始的な対応で解決しました。
途中でコンテナが再起動しなくなってしまった時があり、docker-compose downで落として作り直ししたり。。
この辺はDockerだと気楽ですね。

1
1
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
1
1