Created
April 17, 2013 14:23
-
-
Save douglasjarquin/5404710 to your computer and use it in GitHub Desktop.
Rotate the RDS slow log table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# Usage: ops rds-rotate-slowlog <absolute_path_to_log> | |
# Summary: Use this command to rotate the slow log of on RDS instance. | |
# Help: Queries the slowlog database table maintained by Amazon RDS and outputs it in | |
# the normal MySQL slow log text format. The log file path defaults to | |
# /var/log/mysql/slow_query.log, and can be overriden with a command line argument. | |
# | |
# Examples: | |
# | |
# $ ops rds-rotate-slowlog MYSQL_HOST=localhost MYSQL_USER=root MYSQL_PASSWORD= | |
# $ ops rds-rotate-slowlog ~/Desktop/mysql_slow.log MYSQL_HOST=localhost MYSQL_USER=root MYSQL_PASSWORD= | |
# | |
require 'chronic' | |
require 'chronic_duration' | |
require 'mysql' | |
@mysql = { | |
'host' => ENV['MYSQL_HOST'], | |
'user' => ENV['MYSQL_USER'], | |
'password' => ENV['MYSQL_PASSWORD'] | |
} | |
@sql = Mysql.real_connect(@mysql['host'], @mysql['user'], @mysql['password'], 'mysql') | |
slow_log = ARGV'/var/log/mysql/slow_query.log' | |
f = File.open(slow_log, 'a') | |
slow_queries = @sql.query('SELECT * FROM slow_log;') | |
slow_queries.each_hash do |event| | |
start_time = Chronic.parse(event['start_time']).strftime('%y%m%d %k:%M:%S') | |
f.write "# Time: #{start_time}" | |
f.write "# User@Host: #{event['user_host']}" | |
query_time = ChronicDuration.parse(event['query_time']) | |
lock_time = ChronicDuration.parse(event['lock_time']) | |
f.write "# Query_time: #{query_time} Lock_time: #{lock_time} Rows_sent: #{event['rows_sent']} Rows_examined: #{event['rows_examined']}" | |
sql_text = event['sql_text'] + ';' unless event['sql_text'][-1, 1] == ';' | |
f.write "use #{event['db']};" | |
f.write sql_text | |
f.write "\n" | |
end | |
f.close | |
@sql.query('CALL mysql.rds_rotate_slow_log;') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment