欢迎来到cool的博客
7

Music box

Click to Start

点击头像播放音乐
新博客链接

rails中添加日志: log4r

在ruby中,虽然有自带的logger, 但是跟log4j还是有很大距离的。也很麻烦。 所以,就出现了log4r ( log for ruby ). 

使用步骤 1.新建一个log4r的配置文件: config/log4r.yml

log4r_config:
  # define all loggers ...
  loggers:
    - name      : production
      level     : WARN
      trace     : 'false'
      outputters :
      - datefile
    - name      : development
      level     : DEBUG
      trace     : 'true'
      outputters :
      - datefile

  # define all outputters (incl. formatters)
  outputters:
  - type: DateFileOutputter
    name: datefile
    dirname: "log"
    filename: "my_app.log" # notice the file extension is needed!
    formatter:
      date_pattern: '%H:%M:%S'
      pattern     : '%d %l: %m '
      type        : PatternFormatter

2.修改config/application.rb

require 'rails/all'
# add these line for log4r
require 'log4r'
require 'log4r/yamlconfigurator'
require 'log4r/outputter/datefileoutputter'
include Log4r

Bundler.require(:default, Rails.env) if defined?(Bundler)
module Zurich
  class Application < Rails::Application
    #...
    # assign log4r's logger as rails' logger.
    log4r_config= YAML.load_file(File.join(File.dirname(__FILE__),"log4r.yml"))
    YamlConfigurator.decode_yaml( log4r_config['log4r_config'] )
    config.logger = Log4r::Logger[Rails.env]
  end
end

3.修改Gemfile, 增加log4r的配置. 注意版本不能低于 1.1.9.否则不支持每日分卷

gem 'log4r', '1.1.9'

4.如果你用的是Rails4, 那么需要增加下面这个文件

# config/initializers/log4r_patch_for_rails4.rb
class Log4r::Logger
  def formatter()
  end
end

现在就可以了。 进入到你的 Rails.root, 重启rails, 就会发现log目录开始分卷了。

May  9 17:05 rails_2011-05-09.log
May 10 13:42 rails_2011-05-10.log

日志的内容看起来如下:

$ tail log/rails_2011-05-10.log
Started GET "/????_settings/19/edit" for 127.0.0.1 at ...
13:42:11 INFO:   Processing by ????SettingsController ...
13:42:11 INFO:   Parameters: {"id"=>"19"}
13:42:12 DEBUG:   ????Setting Load (0.0ms)  SELECT "d ...
13:42:12 INFO: Completed 200 OK in 750ms

 

如果再开发环境下,直接在 rails server 那个进程显示log.  在config/environments/development.rb中配置:

  logger = ActiveSupport::Logger.new(STDOUT)
  logger.formatter = config.log_formatter
  config.logger = ActiveSupport::TaggedLogging.new(logger)

返回列表