# Logging
Rails makes use of the ActiveSupport::Logger
class to write log information. Other loggers, such as Log4r
, may also be substituted.
Configuration
You can specify an alternative logger in
config/application.rb
or any other environment file, for example:config.logger = Logger.new(STDOUT) config.logger = Log4r::Logger.new("Application Log")
1
2Or in the
Initializer
section, add any of the followingRails.logger = Logger.new(STDOUT) Rails.logger = Log4r::Logger.new("Application Log")
1
2Log Levels
When something is logged, it's printed into the corresponding log if the log level of the message is equal to or higher than the configured log level. If you want to know the current log level, you can call the
Rails.logger.level
method.The available log levels are:
:debug
,:info
,:warn
,:error
,:fatal
, and:unknown
, corresponding to the log level numbers from 0 up to 5, respectively. To change the default log level, useconfig.log_level = :warn # In any environment initializer, or Rails.logger.level = 0 # at any time
1
2This is useful when you want to log under development or staging without flooding your production log with unnecessary information.
Writing Log Messages
To write in the current log use the
logger.(debug|info|warn|error|fatal|unknown)
method from within a controller, model, or mailer:logger.debug "Person attributes hash: #{@person.attributes.inspect}" logger.info "Processing the request..." logger.fatal "Terminating application, raised unrecoverable error!!!"
1
2
3Tagged Logging
When running multi-user, multi-account applications, it's often useful to be able to filter the logs using some custom rules.
TaggedLogging
in Active Support helps you do exactly that by stamping log lines with subdomains, request ids, and anything else to aid debugging such applications.logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT)) logger.tagged("BCX") { logger.info "Stuff" } # Logs "[BCX] Stuff" logger.tagged("BCX", "Jason") { logger.info "Stuff" } # Logs "[BCX] [Jason] Stuff" logger.tagged("BCX") { logger.tagged("Jason") { logger.info "Stuff" } } # Logs "[BCX] [Jason] Stuff"
1
2
3
4