How to enable MySQL Query Log?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Enabling MySQL query logging is an essential task for database administrators and developers who want to monitor and analyze the queries running on their MySQL server. Query logs help in identifying slow queries, diagnosing performance issues, auditing database activity and much more. This article explains how to enable MySQL query logging with technical details, examples, and additional insights.
Types of MySQL Query Logs
MySQL supports several types of logs to help with query analysis:
- General Query Log: Logs all SQL queries received by the server. Useful for debugging, but can result in large log files.
- Slow Query Log: Logs queries that take longer than a specified duration to execute. Useful for performance tuning.
Steps to Enable MySQL Query Logs
Enabling the General Query Log
The general query log can be enabled by modifying the MySQL configuration file, my.cnf (my.ini on Windows), or dynamically through SQL commands.
Step 1: Configuration via my.cnf
general_log = 1enables the general log.general_log_filespecifies the file location for the log.
Step 2: Dynamic Configuration
To verify the settings:
Enabling the Slow Query Log
The slow query log is typically preferred for performance tuning because it only logs queries that exceed a specified duration.
Step 1: Configuration via my.cnf
slow_query_log = 1enables the slow query log.slow_query_log_filesets the destination for the log file.long_query_timeindicates the threshold in seconds for query execution.
Step 2: Dynamic Configuration
To confirm the settings:
Maintenance and Best Practices
- Rotate Logs: Log rotation helps in managing disk space effectively. Use tools like
logrotateon Linux for automatic log rotation. - Monitor Disk Usage: Constantly monitor disk usage as query logs can grow quickly, especially general logs.
- Use Log Analysis Tools: Utilize log analysis tools such as pt-query-digest to parse and analyze log files for performance optimization.
- Security: Ensure logs are stored in secured directories and accessed by authorized users only.
Sample Query Log Format
A typical general query log entry looks like this:
A slow query log format:
Summary Table
| Log Type | Description | Key Configuration Options |
| General Query Log | Logs all queries received by the server | general_log, general_log_file |
| Slow Query Log | Logs queries exceeding the long_query_time threshold | slow_query_log, slow_query_log_file,
long_query_time |
The ability to toggle query logging on and off dynamically without restarting the server is a powerful feature that gives DBAs flexibility in monitoring and diagnosing issues. Administrators should always consider the potential performance impact of logging, especially with the general query log, and keep log maintenance and security in mind.

