From e63a40efdd6f3f1808cb6ca13a44f25bc6b554f7 Mon Sep 17 00:00:00 2001 From: Masahiro Nakagawa Date: Fri, 8 Nov 2013 16:26:56 +0900 Subject: [PATCH] Add last_error method to FluentLogger. fix #11 --- README.rdoc | 6 ++++-- lib/fluent/logger/fluent_logger.rb | 19 +++++++++++++------ 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/README.rdoc b/README.rdoc index 3448cf5..29dd29c 100644 --- a/README.rdoc +++ b/README.rdoc @@ -9,8 +9,10 @@ A structured event loger require 'fluent-logger' log = Fluent::Logger::FluentLogger.new(nil, :host=>'localhost', :port=>24224) - log.post("myapp.access", {"agent"=>"foo"}) - + unless log.post("myapp.access", {"agent"=>"foo"}) + p log.last_error # You can get last error object via last_error method + end + # output: myapp.access {"agent":"foo"} === Singleton diff --git a/lib/fluent/logger/fluent_logger.rb b/lib/fluent/logger/fluent_logger.rb index b998277..474fa4e 100644 --- a/lib/fluent/logger/fluent_logger.rb +++ b/lib/fluent/logger/fluent_logger.rb @@ -94,15 +94,19 @@ def initialize(tag_prefix, *args) end end + @last_error = nil + begin connect! - rescue + rescue => e + @last_error = e @logger.error "Failed to connect fluentd: #{$!}" @logger.error "Connection will be retried." end end attr_accessor :limit, :logger, :log_reconnect_error_threshold + attr_reader :last_error def post_with_time(tag, map, time) @logger.debug { "event: #{tag} #{map.to_json}" rescue nil } @@ -115,7 +119,8 @@ def close if @pending begin send_data(@pending) - rescue + rescue => e + @last_error = e @logger.error("FluentLogger: Can't send logs to #{@host}:#{@port}: #{$!}") end end @@ -154,7 +159,8 @@ def suppress_sec def write(msg) begin data = to_msgpack(msg) - rescue + rescue => e + @last_error = e @logger.error("FluentLogger: Can't convert to msgpack: #{msg.inspect}: #{$!}") return false end @@ -177,7 +183,8 @@ def write(msg) send_data(@pending) @pending = nil true - rescue + rescue => e + @last_error = e if @pending.bytesize > @limit @logger.error("FluentLogger: Can't send logs to #{@host}:#{@port}: #{$!}") @pending = nil @@ -215,7 +222,7 @@ def connect! @con.sync = true @connect_error_history.clear @logged_reconnect_error = false - rescue + rescue => e @connect_error_history << Time.now.to_i if @connect_error_history.size > RECONNECT_WAIT_MAX_COUNT @connect_error_history.shift @@ -226,7 +233,7 @@ def connect! @logged_reconnect_error = true end - raise + raise e end def log_reconnect_error