A few more methods to format and beautify Ruby objects in console and logs

This is a sort of quick follow up to the previous post. Since then, I’ve seen a few other tricks that can be used to improve the display of output in a Ruby console, as well as in application logs, to make that information more useful for debugging or, also, for display in a dashboard.

The reason I have been looking for this kind of tricks is that I am now working on a component that should make it easier to investigate problems with applications in a production environment; this component (at a very early stage) works by collecting, parsing and interpreting the information in the application logs in a different way to how this is usually done. One of the goals, however, is also to make it possible to collect as much information as may be required, but without affecting too much the application’s performance.

This is because unfortunately, as I mentioned in the previous post, manipulating what is sent to stdout or to a log file with the purpose of prettifying what gets logged, usually results in some significant performance drawbacks that should seriously be taken into consideration if you wish to prettify logged information in a production environment.

We’ll see what sort of performance penalty I am referring to – with a few examples – in the next post, anyways it can still be useful to prettify information that can help with debugging, at least in development. So, here’s a few more ways of formatting Ruby objects in a console and in logs.

Pretty print of JSON

The module JSON, available by requiring the standard library by the same name, exposes a method named pretty_generate that formats any JSON text passed as argument with indentation and new lines, making it easier to read:


Pretty print of XML

It’s easy to do something similar with any XML text, by using the nokogiri gem as shown below:


If you work frequently with JSON and XML, you can also add a couple shortcuts to your ~/.irbrc file:


Then, to use them in any console:


Pretty print of records and collections of records

Apart from awesome_print we’ve seen in the previous post, there’s another gem, named hirb, that can be even more effective in some cases, but especially with ActiveRecord objects and collections of objects, in that it displays them in a similar way to how tables and query results are formatted in a MySQL console. The easiest way to use it is as follows:


Hirb allows more than this, so be sure to have a look at the documentation.


About the author

Vito Botta

I am a passionate web developer based in Espoo, Finland. Besides computing, I love boxing and good food!

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *

3 + 12 =