Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize Rails log messages to JSON format [closed]

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.

like image 622
conorliv Avatar asked Apr 24 '15 18:04

conorliv


People also ask

Is JSON good for logging?

JSON logging is the best format for storing your logs, and here's why. Usually, we log application data in a file. But we need a better framework. If we write logs as JSON, we can easily search fields with a JSON key.

Where does rails logger write to?

By default it puts these log files in the log/ directory of your project. So if you open up that folder you'll see a development.

How do I view rails logs?

In a Rails app, logs are stored under the /log folder. In development mode, the development. log file is used & you see log output on the terminal you're running rails server on.

What is rails logger debugging?

logger. debug , or in short logger. debug writes the parameter text to a log file. This log file is by default environment specific. If you are currently running rails in development environment then the log file in use is log/development.


1 Answers

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
like image 137
Shadwell Avatar answered Sep 20 '22 20:09

Shadwell