在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  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值