Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling MySQL general query log with JDBC

Is there a way to enable MySQL general query logging through JDBC? The closest thing I have found through my search is the ability to log slow queries through JDBC (http://dev.mysql.com/doc/refman/5.5/en/connector-j-reference-configuration-properties.html). Maybe I should do that and set the slow query threshold to 0 ms?

I would like to log all queries through MySQL in a human-readable format and would like to specify the location where the log file should be written. I know I will take a performance hit, but my application only has one user and is simple enough that I would be surprised if the performance hit was noticeable. I would like to try it out anyway to see.

I believe another option I have is to turn on binary logging and use mysqlbinlog to convert the binary logs to a human-readable format, but it sounds like the general query log would provide a simpler means of getting what I want.

like image 281
alfredough Avatar asked Jun 05 '12 18:06

alfredough


People also ask

How do I enable general logging in MySQL?

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.

Does JDBC work with MySQL?

To connect to MySQL from Java, you have to use the JDBC driver from MySQL. The MySQL JDBC driver is called MySQL Connector/J. You find the latest MySQL JDBC driver under the following URL: http://dev.mysql.com/downloads/connector/j. The download contains a JAR file which we require later.


1 Answers

You can enable logging in the JDBC URL like this:

jdbc:mysql://host/db?logger=com.mysql.jdbc.log.Log4JLogger&profileSQL=true

Other logging backends are available (CommonsLogger, Slf4jLogger, JDK14Logger). I believe direct Log4J logging was dropped at some point due to licencing issues so it might not work with your version of the JDBC driver.

Naturally, you'll need the relevant logging library's JAR in your classpath, and a configuration file (log4j.properties). I would set the root level to TRACE first to see what's happening and tighten it up by log level and category once you see what's being logged.

Further reading:

  • https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html
  • http://docs.oracle.com/cd/E17952_01/mysql-monitor-2.3-en/mem-qanal-using-cj.html

HTH

like image 144
Frans Avatar answered Sep 24 '22 14:09

Frans