Define a custom lograge formatter

This post describes how you can use a custom class or module as a formatter for lograge. Sometimes having a class or module to handle more complex log formats can be very useful.

When a proc or lambda gets too big it makes sense to put the code somewhere else. Lograge will expect a call(data) method on whatever you pass it. This either can be an instance of a class or a module itself.

Most of the time a formatter does not have any internal state so we can use a module:

module CustomFormatter

  def call(data)
    # here you have access to the whole data


The method module_function allows us to call the formatter like this: which is exactly what we want.

Now we need to specify the newly formed formatter and pass it to lograge. In our application.rb we add the following (assuming that the file is placed in lib/utils and called custom_formatter.rb

require File.expand_path("../../lib/utils/custom_formatter", __FILE__)
config.lograge.formatter = Contentful::CustomFormatter

Now we are able to use the formatter as intended and have full control over it.

An instance of a class can also be used, then we need to call .new on the formatter and remove the module_function directive.