18

I'm using Rails.logger.debug print variables for debugging purposes. The issue is it prints hashes in an impossible to read format (can't distinguish keys from values). For example, I add the following lines to my code base

#code_base.rb
 my_hash = {'a' => 'alligator', 'b'=>'baboon'}
 Rails.logger.debug my_hash

Then I launch my rails app and type

  tail -f log/development.log 

But when my_hash gets printed, it looks like

  bbaboonaalligator

The key and values are scrunched up, making it impossible to parse. Do you guys know what I should do to fix this?

User314159
  • 7,733
  • 9
  • 39
  • 63

5 Answers5

22

Nevermind, I found the answer to my own question. I need to use

my_hash = {'a' => 'alligator', 'b'=>'baboon'}
Rails.logger.debug "#{my_hash.inspect}"

Then, it looks like

{"b"=>"baboon", "a"=>"aligator"}
User314159
  • 7,733
  • 9
  • 39
  • 63
15

It's even easier to read it when you use to_yaml eg:

logger.debug my_hash.to_yaml

Which is an easy to read format over multiple lines. The inspect method simply spews out a string.

LpLrich
  • 2,463
  • 2
  • 20
  • 31
  • Great tip here! `to_yaml` also creates a string, but it's formatted with `\n` and indentation so it's much easier to skim a large or nested hash… If you're trying to log a hash-like object (say, `params`), you may end up with `ivars` clogging the data you're interested in. Turn it into a normal hash first and then turn that into yaml: `logger.debug params.to_hash.to_yaml` – alxndr Jan 30 '18 at 23:40
2
my_hash = {'a' => 'alligator', 'b'=>'baboon'}
logger.debug "#{my_hash}"

Then, it looks like

{"b"=>"baboon", "a"=>"aligator"}

do not need inspect

lijinma
  • 2,914
  • 1
  • 23
  • 22
1

There is an another way to do this. There is a ruby built in module pp.rb that is Pretty-printer for Ruby objects.

non-pretty-printed output by p is:

#<PP:0x81fedf0 @genspace=#<Proc:0x81feda0>, @group_queue=#<PrettyPrint::GroupQueue:0x81fed3c @queue=[[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], []]>, @buffer=[], @newline="\n", @group_stack=[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], @buffer_width=0, @indent=0, @maxwidth=79, @output_width=2, @output=#<IO:0x8114ee4>>

pretty-printed output by pp is:

#<PP:0x81fedf0
 @buffer=[],
 @buffer_width=0,
 @genspace=#<Proc:0x81feda0>,
 @group_queue=
  #<PrettyPrint::GroupQueue:0x81fed3c
   @queue=
    [[#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
     []]>,
 @group_stack=
  [#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
 @indent=0,
 @maxwidth=79,
 @newline="\n",
 @output=#<IO:0x8114ee4>,
 @output_width=2>
Engr. Hasanuzzaman Sumon
  • 2,103
  • 3
  • 29
  • 38
1

For more complex objects even with ActiveRecord, this could be achieved with a JSON.pretty_generate

Rails.logger.debug JSON.pretty_generate(my_hash.as_json)
Mosaaleb
  • 1,028
  • 1
  • 9
  • 23