Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable per table sql statement logging in mysql

Tags:

logging

mysql

I would like to log all SQL statements that access a specific or a list of specific tables, but not ALL tables.

Is this even possible in MySQL ?

like image 224
Benjamin Avatar asked Mar 13 '12 15:03

Benjamin


People also ask

How do I enable MySQL query logging?

To disable or enable the general query log or change the log file name at runtime, use the global general_log and general_log_file system variables. Set general_log to 0 (or OFF ) to disable the log or to 1 (or ON ) to enable it.

What is general log in MySQL?

MySQL Server provides flexible control over the destination of output written to the general query log and the slow query log, if those logs are enabled. Possible destinations for log entries are log files or the general_log and slow_log tables in the mysql system database.

How do I disable slow query log in MySQL?

To disable or enable the slow query log or change the log file name at runtime, use the global slow_query_log and slow_query_log_file system variables. Set slow_query_log to 0 to disable the log or to 1 to enable it.


2 Answers

No - the general query log is your only option for logging queries - and this is server wide ... although you could log to a table and then delete the results you dont require

like image 171
Manse Avatar answered Nov 15 '22 05:11

Manse


This is possible using Percona Toolkit's pt-query-digest.

If you'd like to monitor all SELECTs, UPDATEs, and JOINs touching table_one, table_two, and table_three on my_database, running something like this on your database server will do the trick:

tcpdump -s 65535 -x -nn -q -tttt -i any -c 1000 port 3306 |
pt-query-digest --type tcpdump \
                --run-time 5s \
                --iterations 0 \
                --filter '$event->{fingerprint} =~ m/\b(from|join|into)\s+(`?my_database`?\.)`?(table_one|table_two|table_three)`?\b/' \
                --output slowlog \
                --no-report

This monitors all your incoming database traffic using tcpdump and pipes it into the pt-query-digest tool, which then attempts to filter that down to the queries on those tables. The output will look something like MySQL's slow query log.

You will need to adjust the regular expression in the --filter argument to fit your needs. As is the case with most regular expressions, there are going to be a lot of edge cases. I tried to cover a few of them, but I am by no means an expert when it comes to regular expressions.

This is not a perfect solution, but it has done the trick for me in certain situations where using the general query log is prohibited.

like image 30
Tristan Avatar answered Nov 15 '22 03:11

Tristan