ITeye博客

在pseudo-model中使用logger

sean · 2007-07-03 22:51 · rubyonrails · Markdown

用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. end
  7. # use logger in model
  8. class Product < ActiveRecord::Base
  9. def products_on_sale
  10. logger.info "products_on_sale"
  11. end
  12. 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)

暂无评论。

评论功能维护中,当前仅展示历史评论。