15

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.

Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
Conor Livingston
  • 905
  • 1
  • 8
  • 17

1 Answers1

23

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
Vadym Tyemirov
  • 8,288
  • 4
  • 42
  • 38
Shadwell
  • 34,314
  • 14
  • 94
  • 99
  • 1
    Where would you put the `MySimpleFormatter` code? – Conor Livingston Apr 27 '15 at 14:10
  • 1
    Anywhere rails can access it really: `lib/my_simple_formatter.rb` for example. – Shadwell Apr 27 '15 at 14:17
  • 4
    Here's something using Lograge and Airbrake so you have complete logging for informations and errors. In config/initializers: [config/initializers/json_logger.rb](https://gist.github.com/Marinlemaignan/d3811105f098e0fa56af) – hatenine Aug 22 '15 at 10:44