con*_*liv 9 json ruby-on-rails logstash
我需要在我的Rails应用程序中将日志消息自定义为JSON格式.
为了说明,目前我的应用程序生成的日志消息如下所示:
I, [2015-04-24T11:52:06.612993 #90159] INFO -- : Started GET "/time_entries" for ::1 at 2015-04-24 11:52:06 -0400
Run Code Online (Sandbox Code Playgroud)
因此,上面一行的日志消息将写入我的日志.
我需要将此格式更改为JSON.如何使日志输出的格式与以下示例完全相同?
{
"type" : "info",
"time" : "2015-04-24T11:52:06.612993",
"message" : "Started GET "/time_entries" for ::1 at 2015-04-24 11:52:06 -0400"
}
Run Code Online (Sandbox Code Playgroud)
注意:它不需要像我的例子那样漂亮打印,它只需要具有JSON格式.
Sha*_*ell 15
您可以配置rails以指定您自己的日志格式化程序:
config.log_formatter定义Rails记录器的格式化程序.此选项默认为除生产之外的所有模式的ActiveSupport :: Logger :: SimpleFormatter实例,默认为Logger :: Formatter.
您可以提供自己的类来输出日志信息:
class MySimpleFormatter < ActiveSupport::Logger::SimpleFormatter
def call(severity, timestamp, _progname, message)
{
type: severity,
time: timestamp,
message: message
}.to_json
end
end
Run Code Online (Sandbox Code Playgroud)
要配置新类,您需要添加配置行:
config.log_formatter = MySimpleFormatter.new
Run Code Online (Sandbox Code Playgroud)