How to customize Rails log messages to JSON format

conorliv picture conorliv · Apr 24, 2015 · Viewed 10.4k times · Source

I need to customize log messages to a JSON format in my Rails app.

To illustrate, currently the log messages my app produces look like this:

I, [2015-04-24T11:52:06.612993 #90159]  INFO -- : Started GET "/time_entries" for ::1 at 2015-04-24 11:52:06 -0400

As a result, log messages like the line above get written to my log.

I need to change this format to JSON. How can I make the log output formatted exactly like the following example?

{
  "type" : "info",
  "time" : "2015-04-24T11:52:06.612993",
  "message" : "Started GET "/time_entries" for ::1 at 2015-04-24 11:52:06 -0400"
}

Note: It doesn't need to be pretty printed like my example, it just has to have the JSON format.

Answer

Shadwell picture Shadwell · Apr 24, 2015

You can configure rails to specify your own log formatter:

config.log_formatter defines the formatter of the Rails logger. This option defaults to an instance of ActiveSupport::Logger::SimpleFormatter for all modes except production, where it defaults to Logger::Formatter.

You can provide your own class to output the log information:

class MySimpleFormatter < ActiveSupport::Logger::SimpleFormatter
  def call(severity, timestamp, _progname, message)
    { 
      type: severity,
      time: timestamp,
      message: message
    }.to_json
  end
end

To configure your new class you'd need to add a config line:

config.log_formatter = MySimpleFormatter.new