用rubyonrails开发已有三个月左右, 还没有在model中使用过logger.今天碰巧需要在一个pseudo-model(不继承ActiveRecord::Base, 即不对应数据库中的表)中使用logger, 突然不知道应该从哪里获取logger.如果在Controller和Model的方法中, 可以直接引用logger, 例如:
看了一下
wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging ,基本明白了rails中logger工作原理:
logger的配置是由environment.rb初始化完成的,主要有两个步骤,
首先为整个rails环境定义了一个默认的全局logger:
接着将这个logger 分别分配给rails中的主要的components: ActiveRecord, ActionController, ActionMailer
根据以上原理, 我们可以得出结论:
ruby 代码
- # use logger in controller
- class ProductsController < ApplicationController
- def index
- logger.info 'index action....'
- end
- end
- # use logger in model
- class Product < ActiveRecord::Base
- def products_on_sale
- logger.info "products_on_sale"
- end
- end
logger的配置是由environment.rb初始化完成的,主要有两个步骤,
首先为整个rails环境定义了一个默认的全局logger:
ruby 代码
- begin
- RAILS_DEFAULT_LOGGER = Logger.new("#{RAILS_ROOT}/log/#{RAILS_ENV}.log")
- rescue StandardError
- RAILS_DEFAULT_LOGGER = Logger.new(STDERR)
- RAILS_DEFAULT_LOGGER.level = Logger::WARN
- RAILS_DEFAULT_LOGGER.warn(
- "Rails Error: Unable to access log file. Please ensure that log/#{RAILS_ENV}.log exists and is chmod 0666. " +
- "The log level has been raised to WARN and the output directed to STDERR until the problem is fixed."
- )
- end
接着将这个logger 分别分配给rails中的主要的components: ActiveRecord, ActionController, ActionMailer
ruby 代码
- [ActiveRecord, ActionController, ActionMailer].each { |mod| mod::Base.logger ||= RAILS_DEFAULT_LOGGER }
根据以上原理, 我们可以得出结论:
- 在ActiveRecord/ActionController/ActionMailer中我们可以直接引用logger(如上面代码所示)
- 在除这些rails主要的component之外的类中,可以直接引用全局常量:RAILS_DEFAULT_LOGGER,例如:
ruby 代码
- # this is a pseudo-model class, so it does not associate with any specific rails class
- class CartItem
- def price
- RAILS_DEFAULT_LOGGER.info 'in price method'
- end
- end