日志工具 Log4r

Ruby Ruby on Rails

使用 log4r 对日志进行管理

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

注: rails5 有时候会报错 Log4r 未定义的方法 加上这个文件后便不会报错了

现在就可以了。 进入到你的 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
评论数量: 0

0
点赞
593
浏览
0
评论

贡献 1
babyhai
保持一颗平常心 ,做自己喜欢的事儿 学习rails之旅