Skip to content

Instantly share code, notes, and snippets.

@akira345
Last active December 27, 2017 12:08
Show Gist options
  • Select an option

  • Save akira345/f2c1d7a22e14bb9dea7e28507cfefd7f to your computer and use it in GitHub Desktop.

Select an option

Save akira345/f2c1d7a22e14bb9dea7e28507cfefd7f to your computer and use it in GitHub Desktop.
RDSのログファイルを一括ダウンロードするスクリプトです。日付ごとにディレクトリを作成して格納します。
# -*- coding: utf-8 -*-
#
#
# RDSのログファイルをダウンロードするスクリプトです。
# MySQLでテストしてます。
# 要 AWS SDK for Ruby V2
#
require 'aws-sdk-core'
require 'yaml'
require 'pp'
config = YAML.load(File.read('config.yml'))
Aws.config[:credentials] = Aws::Credentials.new(config['access_key_id'], config['secret_access_key'])
rds = Aws::RDS::Client.new(region: config['region'])
# 設定
db_instance_identifier = 'mysql-db' # インスタンス名
log_base_path = './log/' # ログファイルの保存先。最後にスラッシュをつける。
# ログを取得
rds.describe_db_log_files(db_instance_identifier: db_instance_identifier).each_page do |logs|
logs.describe_db_log_files.each do |log|
# タイムスタンプ取得
timestamp = log.last_written / 1000 # ファイルのタイムスタンプ
str_timestamp = Time.at(timestamp).strftime('%Y%m%d').to_s
# ディレクトリ作成
log_path = log_base_path + str_timestamp + '/'
FileUtils.mkdir_p(log_path) unless FileTest.exist?(log_path)
# 余計なファイルを除外
next if log.log_file_name == 'mysqlUpgrade'
# ファイル名はslowquery/mysql-slowquery.logのような形式なので、ファイル名だけ抜き出す。
log_file_name = log_path + log.log_file_name.split('/')[1]
pp log_file_name
# 一旦ファイル削除
FileUtils.rm(log_file_name) if FileTest.exist?(log_file_name)
# ログファイルの中身取得
additional_data_pending = true
marker = "0:0"
number_of_lines = 0
while additional_data_pending do
rds.download_db_log_file_portion(db_instance_identifier: db_instance_identifier,
log_file_name: log.log_file_name,
marker: marker,
number_of_lines: number_of_lines).each_page do |data|
# 中身があればファイルへ出力。長いファイルは一発で取れないので、追記で保存する。
File.open(log_file_name, 'a') do |io|
unless data.log_file_data.nil? # log_file_dataがファイルの中身
io.print(data.log_file_data)
end
end
additional_data_pending = data.additional_data_pending
marker = data.marker
end
# タイムスタンプ更新
File.utime(timestamp, timestamp, log_file_name)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment