Friday 9 December 2016

Create every day log file in rails

 /etc/logrotate.conf

                                   OR

I try down one but i face issue when starting serve :

http://blog.teksol.info/2007/06/13/how-to-set-logger-options-in-rails


Today, I was replacing RailsCron and BackgrounDRb with generated Daemons, and I happened to investigate how Rails sets up it’s logger. For the longest time, I knew it was possible to change the options, but I just never investigated how to do it. I thought I’d share my findings so others won’t be in the dark as I was.
Actually doing the replacement is very easy:
config/environment.rb
1 Rails::Initializer.run do |config|
2   config.logger = Logger.new(File.dirname(__FILE__) + "/../log/#{RAILS_ENV}.log")
3 end

That’s it. Have fun. Stop reading… Unless you want more details.
This is essentially what Rails does, except now you have complete control over how theLogger is instantiated.
Some options you might want to investigate:
1 # Keep at most 2 2 megabytes log files
2 config.logger = Logger.new(File.dirname(__FILE__) + "/../log/#{RAILS_ENV}.log", 2, 2*1024*1024)
3 
4 # Create a new log file each day
5 config.logger = Logger.new(File.dirname(__FILE__) + "/../log/#{RAILS_ENV}.log", "daily")

If you are running a script which loads the Rails environment manually, you can also do this:
lib/daemons/futures_worker.rb
 1 #!/usr/bin/env ruby
 2 
 3 # You might want to change this
 4 raise "No RAILS_ENV defined" if ENV["RAILS_ENV"].to_s.empty?
 5 
 6 require "logger"
 7 
 8 RAILS_DEFAULT_LOGGER = Logger.new(File.dirname(__FILE__) + "/../../log/futures_runner.rb.log", 3, 2*1024*1024)
 9 require File.dirname(__FILE__) + "/../../config/environment"
10 
11 # Other code as appropriate

The Rails::Initializer is smart enough to use either the RAILS_DEFAULT_LOGGER or the one defined in the configuration block. For the gory details, please read Rails::Initializer#initialize_logger

No comments:

Post a Comment