`
sean
  • 浏览: 15923 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

在pseudo-model中使用logger

阅读更多
用rubyonrails开发已有三个月左右, 还没有在model中使用过logger.今天碰巧需要在一个pseudo-model(不继承ActiveRecord::Base, 即不对应数据库中的表)中使用logger, 突然不知道应该从哪里获取logger.如果在Controller和Model的方法中, 可以直接引用logger, 例如:
ruby 代码
 
  1. # use logger in controller  
  2. class ProductsController < ApplicationController  
  3.     def index  
  4.       logger.info 'index action....'  
  5.     end   
  6.   
  7. end   
  8.   
  9. # use logger in model  
  10. class Product < ActiveRecord::Base  
  11.     def products_on_sale  
  12.         logger.info "products_on_sale"  
  13.     end  
  14. end   
看了一下wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging ,基本明白了rails中logger工作原理:
logger的配置是由environment.rb初始化完成的,主要有两个步骤,
首先为整个rails环境定义了一个默认的全局logger:
ruby 代码
 
  1. begin  
  2.   RAILS_DEFAULT_LOGGER = Logger.new("#{RAILS_ROOT}/log/#{RAILS_ENV}.log")  
  3. rescue StandardError  
  4.   RAILS_DEFAULT_LOGGER = Logger.new(STDERR)  
  5.   RAILS_DEFAULT_LOGGER.level = Logger::WARN  
  6.   RAILS_DEFAULT_LOGGER.warn(  
  7.     "Rails Error: Unable to access log file. Please ensure that log/#{RAILS_ENV}.log exists and is chmod 0666. " +  
  8.     "The log level has been raised to WARN and the output directed to STDERR until the problem is fixed."   
  9.   )  
  10. end  

接着将这个logger分别分配给rails中的主要的components: ActiveRecord, ActionController, ActionMailer
ruby 代码
  1. [ActiveRecord, ActionController, ActionMailer].each { |mod| mod::Base.logger ||= RAILS_DEFAULT_LOGGER }  

根据以上原理, 我们可以得出结论:

  1. 在ActiveRecord/ActionController/ActionMailer中我们可以直接引用logger(如上面代码所示)
  2. 在除这些rails主要的component之外的类中,可以直接引用全局常量:RAILS_DEFAULT_LOGGER,例如:
ruby 代码
  1. # this is a pseudo-model class, so it does not associate with any specific rails class
  2. class CartItem  
  3.   def price  
  4.      RAILS_DEFAULT_LOGGER.info 'in price method'  
  5.   end  
  6. end  

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics