1. change log.rb to json_logger.rb 2. change Log to JSONLogger 3. change datetime to time 4. don't output empty values 5. msg use hash or string(originally json or string)
Signed-off-by: Wu Zhende wuzhende666@163.com --- lib/{log.rb => json_logger.rb} | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) rename lib/{log.rb => json_logger.rb} (65%)
diff --git a/lib/log.rb b/lib/json_logger.rb similarity index 65% rename from lib/log.rb rename to lib/json_logger.rb index aad00ca..6d1173e 100644 --- a/lib/log.rb +++ b/lib/json_logger.rb @@ -6,7 +6,7 @@ require 'logger' require 'json'
# print logs in JSON format -class Log < Logger +class JSONLogger < Logger LEVEL_INFO = { 'DEBUG' => 0, 'INFO' => 1, @@ -18,21 +18,19 @@ class Log < Logger
FORMATTER = proc { |severity, datetime, progname, msg| level_num = LEVEL_INFO[severity] - begin - message = JSON.parse(msg) - rescue JSON::ParserError - message = { 'message' => msg } - end - h = { + logger_hash = { 'level' => severity.to_s, 'level_num' => level_num, - 'datetime' => datetime, - 'progname' => progname, - 'message' => '' + 'time' => datetime } - h.merge!(message) - h.merge!({ 'caller' => caller }) if level_num >= 2 - h.to_json + + logger_hash['progname'] = progname if progname + logger_hash['caller'] = caller if level_num >= 2 + + msg = { 'message' => msg } unless msg.is_a?(Hash) + logger_hash.merge!(msg) + + logger_hash.to_json }
def initialize(logdev = STDOUT, formatter = FORMATTER)