问题
I'm new to Ruby/Rails programming and still finding my way. I have created a sample web app by following this tutorial. It's working fine. It's using Ruby version 1.9.3 with Rails version 4.0.8.
However I would like to implement logging. So I inserted the following lineq into one of my controllers:
logger.debug "Hello! I'm a DEBUG message"
logger.info "Hello! I'm an INFO message"
This produced the following logs:
Hello! I'm a DEBUG message
Hello! I'm an INFO message
That's not too helpful. I want to see more details in the log output. When was this log created? What was the log level? What is the filename and line number of this log? I want to see all of that.
So I implemented the solution described here by creating a file config/initializers/logger.rb with the following contents:
class Logger::SimpleFormatter
def call(severity, time, progname, msg)
"[#{severity} #{time} #{caller(0).first.match(/.*:\d+/)[0]}] #{msg}\n"
end
end
But it makes no difference. The log lines still come out bare, without any of the other essential information I'm looking for. How to fix this? Why didn't creating my logger.rb have any effect?
回答1:
In Rails 4, the default logger for all modes (except production) is ActiveSupport::Logger::SimpleFormatter. See the documentation here: http://guides.rubyonrails.org/configuring.html#rails-general-configuration
So, your logger.rb needs to be:
class ActiveSupport::Logger::SimpleFormatter
def call(severity, time, progname, msg)
"[#{severity} #{time} #{caller(0).first.match(/.*:\d+/)[0]}] #{msg}\n"
end
end
Please note that this will not work in production mode. For production you will have to customize Logger::Formatter if you need to.
回答2:
I sincerely do not understand why the logging in rails is so "bare". The default logger rails use is even better, but rails dumbs it further down.
Things I need in logging:
- timestamp
- severity
- preferable host-process (for joining multiple logfiles)
There are some good alternatives though, you can have a look at :
- log4r: a powerful logger, I have used it a few times, but not documented very well. Also not sure if it is still maintained.
- recently I keep using better_logging which is a little less powerful, but needs less configuration to be usable out of the box, and the default serves my needs perfectly (and the custom-string option is then the finishing touch).
来源:https://stackoverflow.com/questions/24605265/how-do-i-get-rails-to-display-standard-useful-information-in-log-statements