Setting up the logger in rails 3
By default, Rails should be logging to an environment-specific log file in your project's log
directory. It will be called either test.log
, development.log
, or production.log
depending on which environment you're running in.
You can log directly to Rails' logger using the Rails.logger
object:
Rails.logger.info "My info message"
Rails.logger.debug "My debugging message"
Rails.logger.warn "My warning message"
Rails used to use Ruby's standard logging class, but it now uses ActiveSupport::BufferedLogger
. (The official Ruby on Rails Guides are incorrect when they say "Rails makes use of Ruby’s standard logger to write log information").
Custom logger in Rails 3?
You could do that with this code
logfile = File.open('/path/to/log.log', 'a')
StatusLogger = Logger.new(logfile)
StatusLogger.info 'Hello World!'
And you would most likely configure this in an initializer file, or you could do it in an environment file if you wanted.
How to initialize a logger in rails 3?
Where should MyLogger be logically placed?
Probably put it under /lib. You can then require it from the initializer where you set the custom logger.
How can you periodically delete the oldest logging information?
There are a countless ways you can do this and choosing will be based on your constraints. You haven't spoken much about your constraints, so it's going to be hard to give you the just-right answer. E.g. you could clean up old logs every time you add a new log entry, you could run a cron job, you could install some non-Rails software that does log rotation and other log maintenance, you could use Papertrail, if you use Heroku you could look up https://devcenter.heroku.com/articles/scheduled-jobs-custom-clock-processes.
Remember Rails is designed more to handle requests and respond to them in the context of that request, than to run maintenance outside of the context of receiving a request. You could do maintenance as a side-effect of every format_message request to MyLogger, checking for the oldest logging entry and if you find one older than a week, delete them. You haven't given a constraint why you can't do this in-process, and if you're prototyping something early and portable, then this would get you going fast.
Rails 3 model logger
You can do this:
Create a custom Logger if you want to format it differently.You can ignore this if format needs to be the same.
class ModelLogger < Logger
def format_message(severity, timestamp, progname, msg)
"#{timestamp.to_formatted_s:)db)} #{severity} #{msg}\n"
end
end
In the config/initializers/ , create logs.rb and add this:
model_logfile = File.open("#{RAILS_ROOT}/log/model.log", 'a')
model_logfile.sync = true
MODEL_LOG = ModelLogger.new(model_logfile)
Now, after you restart your server,
MODEL_LOG.debug "This will be logged to model.log"
MODEL_LOG.error "Errors also can be logged."
How to change Rails 3.0's default log path?
You just need define your logger
config.logger = ActiveSupport::BufferedLogger.new(File.join(ENV['SOME_ENVIRONMENT_VAR'], "var/output/logs/rails.log"))
This trick works with Rails 2 too. And you can define by environment where you really want your log file.
How to configure Log4r with Rails 3.0.x?
Hehe ...The idea of Log4r comes from the famous "Log4j", which is my favorite logger in my java programming life.
However log4r's doc is really poor, and it's really hard for newbies. Let me show my solution:
Step1. create the log4r config file: (file name: config/log4r.yml)
log4r_config:
# define all loggers ...
loggers:
- name : production
level : WARN
trace : 'false'
outputters :
- datefile
- name : development
level : DEBUG
trace : 'true'
outputters :
- datefile
# define all outputters (incl. formatters)
outputters:
- type: DateFileOutputter
name: datefile
dirname: "log"
# notice the file extension is needed!
# if you want the file is named by the process, just comment it,
# then it will automatically get the same name with its process,
# e.g. rails_2017-05-03.log
filename: "my_app.log"
formatter:
date_pattern: '%H:%M:%S'
pattern : '%d %l: %m '
type : PatternFormatter
step2. modify config/application.rb
require 'rails/all'
# add these line for log4r
require 'log4r'
require 'log4r/yamlconfigurator'
require 'log4r/outputter/datefileoutputter'
include Log4r
Bundler.require(:default, Rails.env) if defined?(Bundler)
module Zurich
class Application < Rails::Application
#...
# assign log4r's logger as rails' logger.
log4r_config= YAML.load_file(File.join(File.dirname(__FILE__),"log4r.yml"))
YamlConfigurator.decode_yaml( log4r_config['log4r_config'] )
config.logger = Log4r::Logger[Rails.env]
end
end
step3. add this line to your Gemfile.
# which is the latest version and support "datefileoutputter"
gem 'log4r', '1.1.9'
(if you are using Rails 4+ (including Rails6), there still is step4: add this file to config/initializers folder
# config/initializers/log4r_patch_for_rails4.rb
class Log4r::Logger
def formatter() # for rails4+
Proc.new{|severity, time, progname, msg|
formatted_severity = sprintf("%-5s",severity.to_s)
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S")
"[#{formatted_severity} #{formatted_time} #{$$}]\n #{msg}\n"
}
end
def formatter= temp # for rails6+
end
end
)
It's done. Now "cd" into your Rails application folder, run "bundle" to install log4r, then "rails s",
you will find the log files in "/log" folder like this:
May 9 17:05 rails_2011-05-09.log
May 10 13:42 rails_2011-05-10.log
and the log content is( my favorite format ) :
$ tail log/rails_2011-05-10.log
Started GET "/????_settings/19/edit" for 127.0.0.1 at ...
13:42:11 INFO: Processing by ????SettingsController ...
13:42:11 INFO: Parameters: {"id"=>"19"}
13:42:12 DEBUG: ????Setting Load (0.0ms) SELECT "d ...
13:42:12 INFO: Completed 200 OK in 750ms
My environment:
- OS: cygwin running in XP
- ruby 1.8.7 (2011-02-18 patchlevel 334) [i386-mingw32]
- rails: 3.0.5
- gem: 1.6.0
Any question please let me know~ :-)
refer to: https://stackoverflow.com/a/20154414/445908
,and rails6 log4r tagged_logging.rb:22:in `call': wrong number of arguments
How to get Rails.logger printing to the console/stdout when running rspec?
For Rails 4, see this answer.
For Rails 3.x, configure a logger in config/environments/test.rb
:
config.logger = Logger.new(STDOUT)
config.logger.level = Logger::ERROR
This will interleave any errors that are logged during testing to STDOUT. You may wish to route the output to STDERR or use a different log level instead.
Sending these messages to both the console and a log file requires something more robust than Ruby's built-in Logger class. The logging gem will do what you want. Add it to your Gemfile
, then set up two appenders in config/environments/test.rb
:
logger = Logging.logger['test']
logger.add_appenders(
Logging.appenders.stdout,
Logging.appenders.file('example.log')
)
logger.level = :info
config.logger = logger
Rails3 Custom logger
Rails3 custom logging options?
Can't make rails 3 logger work
The logger is fine, but tail -f isn't working for some reason. I'm so angry right now. See you in serverfault
Related Topics
Rails: Good Rspec2 Example Usage? (Also: Cucumber, Pickle, Capybara)
Should I Define a Main Method in My Ruby Scripts
What Should Be Removed from Public Source Control in Ruby on Rails
Ruby/Rails - Models Named with Two Words (Naming Convention Issues)
How to Change the Position of an Array Element
Combinatory Method Like Tap, But Able to Return a Different Value
Detect Number of Cpus Installed
Set Path for Original Images Using Paperclip in Rails
Can't Install Ruby-Debug-Base19X Gem
Passing Error Messages Through Flash
What's the Difference Between Request.Remote_Ip and Request.Ip in Rails
Hash['Key'] to Hash.Key in Ruby
Are There Good Reasons for 'Private' to Work the Way It Does in Ruby
How to Unit-Test a JSON Controller
Cannot Connect to Remote Db Using Ssh Tunnel and Activerecord