每个动作分隔滑轨日志 [英] Separating rails logs per action

查看:75
本文介绍了每个动作分隔滑轨日志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Rails 3应用程序,可生成许多分析请求.不幸的是,这淹没了日志,我失去了我真正关心的主页请求.我想将这些请求分离到一个单独的日志文件中.有没有一种方法可以指定要转到特定日志文件的特定操作?或者可能是一种降低这些操作的日志记录级别,然后在回读日志文件时仅显示某些级别的日志的方法?

I have rails 3 app that generates a lot of requests for analytics. Unfortunately this drowns the logs and I lose the main page requests that I actually care about. I want to separate these requests in to a separate log file. Is there a way to specify certain actions to go to a certain log file? Or possibly a way to reduce the logging level of these actions, and then only show certain level logs when reading back the log file?

推荐答案

我发现

I found this site, which talked about using a middleware for silencing log actions. I used the same sort of idea and ended up writing a middleware that would swap the logger depending on which action was being called. Here is the middleware, which i put in 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

然后进入config/initializers/noisy_log.rb

And then this goes in config/initializers/noisy_log.rb

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

希望对某人有帮助!

这篇关于每个动作分隔滑轨日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆