---
title: "在pseudo-model中使用logger"
author: "sean"
date: "2007-07-03T22:51:00Z"
tags: []
slug: "pseudo-model-logger"
draft: false
lastmod: "2007-07-03T22:51:00Z"
id: 97422
url: "https://sean.iteye.com/blog/97422"
---

用rubyonrails开发已有三个月左右, 还没有在model中使用过logger.今天碰巧需要在一个pseudo-model(不继承ActiveRecord::Base, 即不对应数据库中的表)中使用logger, 突然不知道应该从哪里获取logger.如果在Controller和Model的方法中, 可以直接引用logger, 例如:

ruby 代码

 

01. # use logger in controller
02. class ProductsController &lt; ApplicationController
03. def index
04. logger.info 'index action....'
05. end
06. end
07. # use logger in model
08. class Product &lt; ActiveRecord::Base
09. def products\_on\_sale
10. logger.info "products\_on\_sale"
11. end
12. end

看了一下[wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging](http://wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging) ，基本明白了rails中logger工作原理:  
logger的配置是由environment.rb初始化完成的,主要有两个步骤,  
首先为整个rails环境定义了一个默认的全局logger:

ruby 代码

 

01. begin
02. RAILS\_DEFAULT\_LOGGER = Logger.new("#{RAILS\_ROOT}/log/#{RAILS\_ENV}.log")
03. rescue StandardError
04. RAILS\_DEFAULT\_LOGGER = Logger.new(STDERR)
05. RAILS\_DEFAULT\_LOGGER.level = Logger::WARN
06. RAILS\_DEFAULT\_LOGGER.warn(
07. "Rails Error: Unable to access log file. Please ensure that log/#{RAILS\_ENV}.log exists and is chmod 0666. " +
08. "The log level has been raised to WARN and the output directed to STDERR until the problem is fixed."
09. )
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