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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With