我有一个ruby脚本,我使用GET方法记录系统状态,在日志中返回的输出是这样的:
1.2.3.111 - - [00/Jan/2016:08:21:24 +0000] "GET /service/sys/status HTTP/1.1" 200 15 0.0006
我想以JSON格式记录这些.有没有办法可以做到这一点,虽然我知道这可以通过瘦网络服务器以某种方式完成,但我不知道如何做到这一点.
使用自定义Logger::Formatter
:
require 'logger' logger = Logger.new(STDOUT) # or retrieve the default application logger logger.formatter = proc do |severity, datetime, progname, msg| %Q|{timestamp: "#{datetime.to_s}", message: "#{msg}"}\n| end logger.info "Hello, world!" #? {timestamp: "2016-01-06 10:48:13 +0100", message: "Hello, world!"}
无论您希望消息都有双引号,最好将jsoning委托给专家(来自@aidan):
require 'json' require 'logger' logger = Logger.new(STDOUT) # or retrieve the default application logger logger.formatter = proc do |severity, datetime, progname, msg| JSON.dump(timestamp: "#{datetime.to_s}", message: msg) end logger.info "Hello, world!" #? {timestamp: "2016-01-06 10:48:13 +0100", message: "Hello, world!"}