shadabahmed / logstasher

Awesome rails logs
MIT License
821 stars 136 forks source link

Logstasher custom fields in ApplicationController #150

Open twinster opened 4 years ago

twinster commented 4 years ago

I am trying to log additional custom fields using Logstasher gem.

I need to log some response parameters, but logstasher does not support itself logging response params using configuration, therefore I put the code into after_action method in ApplicationController.

ApplicationController

after_action :set_logstasher_params

  def set_logstasher_params
    if LogStasher.enabled?
      res_params = JSON.parse(response.body.as_json)
      LogStasher.add_custom_fields do |fields|
        fields[:res_params] = res_params
      end
    end
  end

This is logstasher initializer

initializer/logstasher.rb

if LogStasher.enabled?
  LogStasher.add_custom_fields do |fields|
    fields[:request_params] = request.filtered_parameters
    LogStasher::CustomFields.add(:myapi_runtime)
  end

  LogStasher.add_custom_fields_to_request_context do |fields|    
    fields[:request_params] = request.filtered_parameters
  end
end

The problem is next: After starting rails server, first request I send, logs only parameters which are indicated in logstasher.rb except parameters added in ApplicationController.

But After that every request logs everything indicated logstasher.rb as well as ApplicationController method.

Just First request does not log response parameters from ApplicationController method.