kapso
kapso

Reputation: 11903

Rails Tagged Logging

I am using Tagged Logging with Unicorn and using the following configuration in my environment file.

config.logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
config.log_tags = [:uuid]

So far so good.

When it comes to tags, is there a way to -

  1. Print out specific request headers

  2. Print a custom UUID, i.e something that I can generate. The default UUID that rails spits out is too long.

Upvotes: 2

Views: 5277

Answers (1)

jakeonrails
jakeonrails

Reputation: 1895

See some examples from this Gist here https://gist.github.com/2513183

You can add a proc to the log_tags array, which has access to the request object.

You can generate a UUID in that proc, or you can pass something through the request.env from your ApplicationController in a before_filter, like so:

#application_controller.rb
before_filter :set_some_request_env

def set_some_request_env
  request.env['some_var'] = "Happy"
end

# application.rb
config.log_tags = [
  -> request {
    request.env['some_var']
  }
]

Update

You can use the #tagged method to add tags to all log messages sent within a given block.

To get a parameter from your request or controller params into the tagged output, you can do the following:

#application_controller.rb
around_filter :add_tags_to_logs

def add_tags_to_logs
  Rails.logger.tagged(custom_uuid_for_current_user) do
    yield
  end
end

Upvotes: 2

Related Questions