Bogdan Gusiev
Bogdan Gusiev

Reputation: 8305

Log rotation/clearing in Ruby on Rails

How can I setup the automatic cleanup on test.log and development.log in ruby on rails?

Is there a setting to automatically delete dev and test logs on server start and tests run?

Upvotes: 10

Views: 13672

Answers (5)

Ash Moran
Ash Moran

Reputation: 101

After experimenting, I found that Rails initializers are loaded at the right point where you can truncate the file using the standard Ruby File class. I have this in config/initializers/truncate_logs_on_server_start.rb:

if MyRailsApp::Application.config.truncate_logs_on_server_start
  # Making an assumption here that we're logging to a file...
  File.open("log/#{ENV["RAILS_ENV"]}.log", "w") do |log_file|
    log_file.puts("Initializer truncate_logs_on_server_start reset the log file")
    log_file.puts
  end
end

You just then need to set MyRailsApp::Application.config.truncate_logs_on_server_start in application.rb and the various environments.

Upvotes: 0

Abhishek Parolkar
Abhishek Parolkar

Reputation:

In production environment, you really need SyslogLogger ( http://rails-analyzer.rubyforge.org/tools/files/lib/analyzer_tools/syslog_logger_rb.html ) , it lets you write to syslogd, which creansup,rotates your files in distributed setup.

Upvotes: 0

mylescarrick
mylescarrick

Reputation: 1680

The ruby logger is on hand to help you out here - and it has default options for rotation.

Here's what I do:

In environment.rb we define our own logger

new_logger = Logger.new(File.join(RAILS_ROOT, "log", "new_logger_#{RAILS_ENV}.log"), 'daily')
new_logger.formatter = Logger::Formatter.new

This creates our own loggers... with a formatter (so you get timestamps etc), with one per environment, and rotated daily.

Then in the initialization block we ask Rails to use this logger

Rails::Initializer.run do |config|

  config.active_record.logger = new_logger
  config.action_controller.logger = new_logger

  #snip
end

You can obviously see the power here too to have different loggers for active_record and for action_controller - sometimes very useful!

Upvotes: 19

Omar Qureshi
Omar Qureshi

Reputation: 9093

All script/server is, is a ruby script, im sure you could modify it to do something like:

#!/usr/bin/env ruby
require 'fileutils'
FileUtils.rm File.join(File.dirname(__FILE__), log, *.log)
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/server'

Upvotes: 1

Sarah Mei
Sarah Mei

Reputation: 18484

rake log:clear is a rake task that truncates all files that match log/*.log to zero bytes. You could call it in your server start and run tests tasks.

Upvotes: 16

Related Questions