Class: RackLoggingPerProc

Inherits:
Object
  • Object
show all
Defined in:
lib/rack_logging_per_proc.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, log_path_prefix) ⇒ RackLoggingPerProc

Returns a new instance of RackLoggingPerProc.



15
16
17
18
19
# File 'lib/rack_logging_per_proc.rb', line 15

def initialize app, log_path_prefix
  @app = app
  @log_path_prefix = log_path_prefix
  @process_logger = false
end

Class Method Details

.clear_logsObject



11
12
13
# File 'lib/rack_logging_per_proc.rb', line 11

def self.clear_logs
  @@logs = []
end

.logger_mutexObject



3
4
5
# File 'lib/rack_logging_per_proc.rb', line 3

def self.logger_mutex
 @@logger_mutex ||= Mutex.new
end

.logsObject



7
8
9
# File 'lib/rack_logging_per_proc.rb', line 7

def self.logs
  @@logs ||= []
end

Instance Method Details

#call(env) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/rack_logging_per_proc.rb', line 21

def call env
  RackLoggingPerProc.logger_mutex.synchronize do
    unless @process_logger
      @process_logger = ActiveSupport::BufferedLogger.new(@log_path_prefix + "_#{Process.pid}" + ".log")
      @process_logger.debug("\nProcess logging started")
      RAILS_DEFAULT_LOGGER.instance_eval do
        class << self
          def add(severity, message = nil, progname = nil, &block)
            to_return = super
            if to_return
              RackLoggingPerProc.logger_mutex.synchronize do
                RackLoggingPerProc.logs << [severity, to_return.strip]
              end
            end
            to_return
          end
        end
      end
    end
  end
  
  start_time = Time.now
  @app.call(env)    
ensure
  RackLoggingPerProc.logger_mutex.synchronize do
    @process_logger.info("RECEIVE_REQUEST (#{Process.pid}) #{env['REQUEST_METHOD']} #{env['REQUEST_URI']} #{start_time}")        
    RackLoggingPerProc.logs.each do |to_log|
      @process_logger.add(to_log[0], to_log[1])
    end
    @process_logger.info("#{Time.now} (#{Process.pid}) RESPONSE_SENT")
    @process_logger.info("\n")
    @process_logger.flush
    RackLoggingPerProc.clear_logs
  end
end