2011-06-24 31 views
1

我有rails 3应用程序,它会生成很多分析请求。不幸的是,这会淹死日志,我失去了我真正关心的主要页面请求。我想分开这些请求到一个单独的日志文件。有没有办法指定某些操作去某个日志文件?或者可能是减少这些操作的日志级别的方法,然后在回读日志文件时仅显示某些级别的日志?每次操作分离rails日志

+0

尝试http://agilewebdevelopment.com/plugins/tagged_logger –

回答

6

我找到了this site,谈到了使用中间件来消除日志动作。我使用了同样的想法,最后编写了一个中间件,根据被调用的操作来交换记录器。这里是中间件,它在我把LIB/noisy_logger.rb

class NoisyLogger < Rails::Rack::Logger 
    def initialize app, opts = {} 
    @default_log = Rails.logger 

    # Put the noisy log in the same directory as the default log. 
    @noisy_log = Logger.new Rails.root.join('log', 'noisy.log') 

    @app = app 
    @opts = opts 
    @opts[:noisy] = Array @opts[:noisy] 

    super app 
    end 

    def call env 
    if @opts[:noisy].include? env['PATH_INFO'] 
     logfile = @noisy_log 
    else 
     logfile = @default_log 
    end 

    # What?! Why are these all separate? 
    ActiveRecord::Base.logger = logfile 
    ActionController::Base.logger = logfile 
    Rails.logger = logfile 

    # The Rails::Rack::Logger class is responsible for logging the 
    # 'starting GET blah blah' log line. We need to call super here (as opposed 
    # to @app.call) to make sure that line gets output. However, the 
    # ActiveSupport::LogSubscriber class (which Rails::Rack::Logger inherits 
    # from) caches the logger, so we have to override that too 
    @logger = logfile 

    super 
    end 
end 

然后这正好在配置/初始化/ noisy_log.rb

MyApp::Application.config.middleware.swap(
    Rails::Rack::Logger, NoisyLogger, :noisy => "/analytics/track" 
) 

希望帮助别人!

0

一个选项可能会使用像New Relic这样的服务,它会为您提供所需的范围设定(每个操作)。