Skip to content

Instantly share code, notes, and snippets.

@omnikron
Created June 9, 2016 12:22
Show Gist options
  • Save omnikron/740fc9a85a3d87da518158b8a40080e6 to your computer and use it in GitHub Desktop.
Save omnikron/740fc9a85a3d87da518158b8a40080e6 to your computer and use it in GitHub Desktop.
Elegantly logs rails params in aligned `key: value` form
module ElegantLog
extend ActiveSupport::Concern
def elegant_log(params, display_name = nil)
return if params.blank?
spacer
Rails.logger.info display_name || params.delete(:controller).titleize
longest_length = params.keys.sort {|k1, k2| k2.length <=> k1.length}.first.length
params.each do |key, value|
display_aligned(key, value, longest_length)
end
spacer
end
private
def display_aligned(key, value, longest_length)
Rails.logger.info "#{key}:#{' ' * (longest_length - key.length)} #{value.inspect}"
end
def spacer
Rails.logger.info star_line << star_line << "\n"
end
def star_line
"\n" << "*" * 50
end
end
@omnikron
Copy link
Author

omnikron commented Jun 9, 2016

Stick it in app/controllers/concerns and include in individual controllers (or your application controller) like

class ApplicationController < ActionController::API
  include ElegantLog
end

then log params like magic with elegant_log(params, 'optional display title') (default display title is the controller name).

Sample output:

**************************************************
**************************************************

Mail Controller
user_id:          '41425'
source:           'newsletter'
action:           'unsubscribe'
message:          'quit sending me this shite'
complaint_number: 6621

**************************************************
**************************************************

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment