diff --git a/README.md b/README.md index 3fa00fd..72419f7 100644 --- a/README.md +++ b/README.md @@ -148,6 +148,10 @@ Use nonblocking write(`IO#write_nonblock`) instead of normal write(`IO#write`). If `false`, `Logger#post` raises an error when nonblocking write gets `EAGAIN` (i.e. `use_nonblock` must be `true`, otherwise this will have no effect). Default: `true` +#### timeout (Integer) + +Specify a timeout in seconds for connecting. Default: `0` + #### buffer_overflow_handler (Proc) Pass callback for handling buffer overflow with pending data. See "Buffer overflow" section. diff --git a/lib/fluent/logger/fluent_logger.rb b/lib/fluent/logger/fluent_logger.rb index 0afec88..2aef0a2 100644 --- a/lib/fluent/logger/fluent_logger.rb +++ b/lib/fluent/logger/fluent_logger.rb @@ -22,6 +22,7 @@ require 'monitor' require 'logger' require 'json' +require 'timeout' module Fluent module Logger @@ -115,6 +116,8 @@ def initialize(tag_prefix = nil, *args) @wait_writeable = true @wait_writeable = options[:wait_writeable] if options.key?(:wait_writeable) + @timeout = options[:timeout] || 0 + @last_error = {} begin @@ -170,7 +173,9 @@ def create_socket! if @socket_path @con = UNIXSocket.new(@socket_path) else - @con = TCPSocket.new(@host, @port) + @con = Timeout.timeout(@timeout) do + TCPSocket.new(@host, @port) + end if @tls_options context = OpenSSL::SSL::SSLContext.new if @tls_options[:insecure] diff --git a/spec/fluent_logger_spec.rb b/spec/fluent_logger_spec.rb index b597e58..aa67c8c 100644 --- a/spec/fluent_logger_spec.rb +++ b/spec/fluent_logger_spec.rb @@ -6,6 +6,7 @@ require 'logger' require 'stringio' require 'fluent/logger/fluent_logger/cui' +require 'timeout' describe Fluent::Logger::FluentLogger do let(:fluentd) { @@ -434,4 +435,13 @@ def flush(messages) } end end + + it ('support timeout') { + Timeout::timeout(5) do + # Use invalid IP address to make sure that the connection will timeout. + # (192.0.2.0 is a special IP address that can be used in only documentation. Ref. RFC 5737) + logger = Fluent::Logger::FluentLogger.new(nil, host: '192.0.2.0', port: fluentd.port, timeout: 1) + expect(logger.last_error).to be_a_kind_of(Timeout::Error) + end + } end