DB and Log backup’s using Rake Tasks

Add this in your rakefile for taking log and db backup’s.

require ‘fileutils’
namespace :backup do
  #for taking log backup -start
  desc ‘backup log’
  namespace :log do
   desc ‘rake backup:log:all’
   task :all do
    backup_path = File.join(Rails.root, ‘backup’, ‘log’, “#{Date.today.month}”)
    FileUtils.mkdir_p(backup_path) unless File.exist?(backup_path)
    filename = File.join(backup_path, “log_#{Time.now.strftime(“%Y%m%d”)}.tar.gz”)
    cmd = “tar -czvf #{filename} log/*.log”
    `#{cmd}`
    Rake::Task[“log:clear”].invoke if File.size?(filename)
   end
  end
  #for taking log backup -end

  #for taking db backup -start
  desc ‘backup db’
   namespace :db do
   desc ‘rake backup:db:mysql’
   task :mysql => :environment do
    backup_path = File.join(Rails.root, ‘backup’, ‘db’, “#{Date.today.year}-#{Date.today.month}”)
    FileUtils.mkdir_p(backup_path) unless File.exist?(backup_path)
    tmp_filename = File.join(Rails.root, ‘backup’, ‘db’, ‘tmp.sql’)
    filename = File.join(backup_path, “db_#{Rails.env}_#{Time.now.strftime(“%Y%m%d%H%M%S”)}.tar.gz”)
    db_options = YAML.load_file(File.join(Rails.root, ‘config’, ‘database.yml’))[Rails.env].symbolize_keys
    cmd = <<-CMD
        mysqldump  GetProject_development -u root -proot  > #{tmp_filename}
tar -czvf #{filename} backup/db/tmp.sql

    CMD
    `#{cmd}`
   end
  end
#for taking db backup -end
end

That’s it now run

rake backup:log:all

to take a backup of log (you can also run this rake daily once automatically for taking daily backups). This will take a backup of log, and clear the current log file’s contents. Similarly, for taking db backup run

rake backup:db:mysql

All the backups will be stored in a folder named “backup” which will be available at the root path of the app.

Advertisements

1 thought on “DB and Log backup’s using Rake Tasks”

Comments are closed.