Class AbstractLogstashTcpSocketAppender<Event extends DeferredProcessingAware,Listener extends TcpAppenderListener<Event>>
- All Implemented Interfaces:
Appender<Event>,ContextAware,FilterAttachable<Event>,LifeCycle
- Direct Known Subclasses:
LogstashAccessTcpSocketAppender,LogstashTcpSocketAppender
AsyncDisruptorAppender appender that writes
events to a TCP Socket outputStream.
The behavior is similar to a SocketAppender, except that:
- it uses a
RingBufferinstead of aBlockingQueue - it writes using an
Encoderinstead of serialization
In addition, SSL can be enabled by setting the SSL configuration via setSsl(SSLConfiguration).
See the logback manual
for details on how to configure client-side SSL.
- Since:
- 11 Jun 2014 (creation date)
- Author:
- Mirko Bernardoni (original, which did not use disruptor)
-
Nested Class Summary
Nested classes/interfaces inherited from class net.logstash.logback.appender.AsyncDisruptorAppender
AsyncDisruptorAppender.LogEvent<Event>, AsyncDisruptorAppender.LogEventFactory<Event>, AsyncDisruptorAppender.LogEventTranslator<Event> -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intDefault timeout when waiting for the remote server to accept our connection.static final intThe default delay before sending data into a newly established connectionstatic final intThe default port number of remote logging server (4560).static final intDeprecated.static final intThe default reconnection delay (30000 milliseconds or 30 seconds).static final Stringstatic final intstatic final intThe default write timeout in milliseconds (0 means no write timeout).protected static final Stringprotected static final StringFields inherited from class net.logstash.logback.appender.AsyncDisruptorAppender
APPENDER_NAME_FORMAT, DEFAULT_DROPPED_WARN_FREQUENCY, DEFAULT_PRODUCER_TYPE, DEFAULT_RING_BUFFER_SIZE, DEFAULT_WAIT_STRATEGY, listeners, THREAD_INDEX_FORMATFields inherited from class ch.qos.logback.core.UnsynchronizedAppenderBase
name, startedFields inherited from class ch.qos.logback.core.spi.ContextAwareBase
context -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidaddDestination(String destination) Adds the given destination (or destinations) to the list of potential destinations to which to send logs.voidaddDestinations(InetSocketAddress... destinations) Adds the given destinations to the list of potential destinations.protected com.lmax.disruptor.EventHandler<AsyncDisruptorAppender.LogEvent<Event>> Create theEventHandlerto process events as they become available from the RingBuffer.protected voidfireConnectionClosed(Socket socket) protected voidfireConnectionFailed(InetSocketAddress address, Throwable throwable) protected voidfireConnectionOpened(Socket socket) protected voidfireEventSendFailure(Event event, Throwable reason) protected voidfireEventSent(Socket socket, Event event, long durationInNanos) Returns the currently connected destination as anOptional.Get the connection timeout used when establishing a TCP connection to a remote destination.Return the destinations in which to attempt to send logs.protected StringgetHostString(InetSocketAddress destination) Returns the host string from the given destination, avoiding a DNS hit if possible.intDeprecated.useAsyncDisruptorAppender.getRingBufferSize()instead.Deprecated.getSsl()intbooleanbooleanbooleanWhether the write timeout feature is enabled or not.protected Future<?> scheduleReaderCallable(Callable<Void> readerCallable) voidsetConnectionStrategy(DestinationConnectionStrategy destinationConnectionStrategy) voidsetConnectionTimeout(Duration connectionTimeout) Set the connection timeout when establishing a connection to a remote destination.voidsetEncoder(Encoder<Event> encoder) voidsetInitialSendDelay(Duration delay) Time period to wait before sending data into a newly established connection.voidsetKeepAliveCharset(Charset keepAliveCharset) The charset to use when writing thekeepAliveMessage.voidsetKeepAliveDuration(Duration keepAliveDuration) If this duration elapses without an event being sent, then thekeepAliveMessagewill be sent to the socket in order to keep the connection alive.voidsetKeepAliveMessage(String keepAliveMessage) Message to send for keeping the connection alive ifkeepAliveDurationis non-null and strictly positive.voidsetQueueSize(int queueSize) Deprecated.useAsyncDisruptorAppender.setRingBufferSize(int)instead.voidsetReconnectionDelay(Duration delay) Time period for which to wait after failing to connect to all servers, before attempting to reconnect.voidsetSecondaryConnectionTTL(Duration secondaryConnectionTTL) Deprecated.voidsetSocketFactory(SocketFactory socketFactory) Set theSocketFactoryused to create clientSockets to which to communicate.voidsetSsl(SSLConfiguration sslConfiguration) Set this to non-null to use SSL.voidsetThreadNameFormat(String threadNameFormat) Pattern used by the to set the handler thread name.voidsetWriteBufferSize(int writeBufferSize) The number of bytes available in the write buffer.voidsetWriteTimeout(Duration writeTimeout) Sets the time period for which to wait for a write to complete before timing out and attempting to reconnect to that destination.voidstart()voidstop()protected voidMethods inherited from class net.logstash.logback.appender.AsyncDisruptorAppender
addListener, append, calculateThreadName, fireAppenderStarted, fireAppenderStopped, fireEventAppended, fireEventAppendFailed, getAppendRetryFrequency, getAppendTimeout, getDisruptor, getDroppedWarnFrequency, getEventTranslator, getProducerType, getRingBufferSize, getShutdownGracePeriod, getThreadFactory, getThreadNameFormat, getWaitStrategy, isAddDefaultStatusListener, isDaemon, isRingBufferEmpty, prepareForDeferredProcessing, removeListener, safelyFireEvent, setAddDefaultStatusListener, setAppendRetryFrequency, setAppendTimeout, setDaemon, setDroppedWarnFrequency, setEventFactory, setEventTranslator, setProducerType, setRingBufferSize, setShutdownGracePeriod, setThreadFactory, setWaitStrategy, setWaitStrategyTypeMethods inherited from class ch.qos.logback.core.UnsynchronizedAppenderBase
addFilter, clearAllFilters, doAppend, getCopyOfAttachedFiltersList, getFilterChainDecision, getName, setName, toStringMethods inherited from class ch.qos.logback.core.spi.ContextAwareBase
addError, addError, addInfo, addInfo, addStatus, addWarn, addWarn, getContext, getDeclaredOrigin, getStatusManager, setContextMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface ch.qos.logback.core.spi.ContextAware
addError, addError, addInfo, addInfo, addStatus, addWarn, addWarn, getContext, setContext
-
Field Details
-
HOST_NAME_FORMAT
- See Also:
-
PORT_FORMAT
- See Also:
-
DEFAULT_THREAD_NAME_FORMAT
- See Also:
-
DEFAULT_PORT
public static final int DEFAULT_PORTThe default port number of remote logging server (4560).- See Also:
-
DEFAULT_RECONNECTION_DELAY
public static final int DEFAULT_RECONNECTION_DELAYThe default reconnection delay (30000 milliseconds or 30 seconds).- See Also:
-
DEFAULT_WRITE_TIMEOUT
public static final int DEFAULT_WRITE_TIMEOUTThe default write timeout in milliseconds (0 means no write timeout).- See Also:
-
DEFAULT_INITIALSEND_DELAY
public static final int DEFAULT_INITIALSEND_DELAYThe default delay before sending data into a newly established connection- See Also:
-
DEFAULT_QUEUE_SIZE
Deprecated.UseAsyncDisruptorAppender.DEFAULT_RING_BUFFER_SIZEinsteadDefault size of the queue used to hold logging events that are destined for the remote peer. Assuming an average log entry to take 1k, this would result in the application using about 10MB additional memory if the queue is full- See Also:
-
DEFAULT_CONNECTION_TIMEOUT
public static final int DEFAULT_CONNECTION_TIMEOUTDefault timeout when waiting for the remote server to accept our connection. The same timeout is used as a read timeout during SSL handshake.- See Also:
-
DEFAULT_WRITE_BUFFER_SIZE
public static final int DEFAULT_WRITE_BUFFER_SIZE- See Also:
-
-
Constructor Details
-
AbstractLogstashTcpSocketAppender
public AbstractLogstashTcpSocketAppender()
-
-
Method Details
-
createEventHandler
protected com.lmax.disruptor.EventHandler<AsyncDisruptorAppender.LogEvent<Event>> createEventHandler()Description copied from class:AsyncDisruptorAppenderCreate theEventHandlerto process events as they become available from the RingBuffer. This method is invoked when the appender is started byAsyncDisruptorAppender.start()and a newDisruptoris initialized.- Specified by:
createEventHandlerin classAsyncDisruptorAppender<Event extends DeferredProcessingAware,Listener extends TcpAppenderListener<Event>> - Returns:
- a
EventHandlerinstance.
-
isStarted
public boolean isStarted()- Specified by:
isStartedin interfaceLifeCycle- Overrides:
isStartedin classUnsynchronizedAppenderBase<Event extends DeferredProcessingAware>
-
start
public void start()- Specified by:
startin interfaceLifeCycle- Overrides:
startin classAsyncDisruptorAppender<Event extends DeferredProcessingAware,Listener extends TcpAppenderListener<Event>>
-
stop
public void stop()- Specified by:
stopin interfaceLifeCycle- Overrides:
stopin classAsyncDisruptorAppender<Event extends DeferredProcessingAware,Listener extends TcpAppenderListener<Event>>
-
scheduleReaderCallable
-
fireEventSent
-
fireEventSendFailure
-
fireConnectionOpened
-
fireConnectionClosed
-
fireConnectionFailed
-
getEncoder
-
setEncoder
-
getSocketFactory
-
setSocketFactory
Set theSocketFactoryused to create clientSockets to which to communicate. Usenullto use the system default SocketFactory.- Parameters:
socketFactory- the socket factory to use to create connections with remote destinations.
-
addDestination
Adds the given destination (or destinations) to the list of potential destinations to which to send logs.The string is a comma separated list of destinations in the form of hostName[:portNumber].
If portNumber is not provided, then the default (4560<Event extends DeferredProcessingAware,
Listener extends TcpAppenderListener<Event>>) will be used For example, "host1.domain.com,host2.domain.com:5560"
- Parameters:
destination- comma-separated list of destinations in the form ofhostName[:portNumber]- Throws:
IllegalArgumentException
-
addDestinations
Adds the given destinations to the list of potential destinations.- Parameters:
destinations- theInetSocketAddressto add to the list of valid destinations- Throws:
IllegalArgumentException
-
getHostString
Returns the host string from the given destination, avoiding a DNS hit if possible.- Parameters:
destination- theInetSocketAddressto get the host string from- Returns:
- the host string of the given destination
-
updateCurrentThreadName
protected void updateCurrentThreadName() -
getThreadNameFormatParams
- Overrides:
getThreadNameFormatParamsin classAsyncDisruptorAppender<Event extends DeferredProcessingAware,Listener extends TcpAppenderListener<Event>>
-
getDestinations
Return the destinations in which to attempt to send logs.- Returns:
- an ordered list of
InetSocketAddressrepresenting the configured destinations
-
setReconnectionDelay
Time period for which to wait after failing to connect to all servers, before attempting to reconnect. Default is 30000<Event extends DeferredProcessingAware,Listener extends TcpAppenderListener<Event>> milliseconds. - Parameters:
delay- the reconnection delay
-
getReconnectionDelay
-
setInitialSendDelay
Time period to wait before sending data into a newly established connection.- Parameters:
delay- the time to wait before sending the first data
-
getInitialSendDelay
-
setSecondaryConnectionTTL
Deprecated.Convenience method for settingPreferPrimaryDestinationConnectionStrategy.setSecondaryConnectionTTL(Duration). When theconnectionStrategyis aPreferPrimaryDestinationConnectionStrategy, this will set itsPreferPrimaryDestinationConnectionStrategy.setSecondaryConnectionTTL(Duration).- Parameters:
secondaryConnectionTTL- the TTL of a connection when connected to a secondary destination- Throws:
IllegalStateException- if theconnectionStrategyis not aPreferPrimaryDestinationConnectionStrategy- See Also:
-
getSecondaryConnectionTTL
Deprecated.Convenience method for accessingPreferPrimaryDestinationConnectionStrategy.getSecondaryConnectionTTL().- Returns:
- the secondary connection TTL or
nullif the connection strategy is not aPreferPrimaryDestinationConnectionStrategy. - See Also:
-
setConnectionTimeout
Set the connection timeout when establishing a connection to a remote destination. Use0for an "infinite timeout" which often really means "use the OS defaults".- Parameters:
connectionTimeout- connection timeout
-
getConnectionTimeout
Get the connection timeout used when establishing a TCP connection to a remote destination.- Returns:
- the connection timeout (never null).
-
getWriteBufferSize
public int getWriteBufferSize() -
setWriteBufferSize
public void setWriteBufferSize(int writeBufferSize) The number of bytes available in the write buffer. Defaults to 8192<Event extends DeferredProcessingAware,Listener extends TcpAppenderListener<Event>>. If less than or equal to zero, buffering the output stream will be disabled. If buffering is disabled, the writer thread can slow down, but it will also can prevent dropping events in the buffer on flaky connections.
- Parameters:
writeBufferSize- the write buffer size in bytes
-
getQueueSize
Deprecated.useAsyncDisruptorAppender.getRingBufferSize()instead.Returns the maximum number of events in the queue. Alias forAsyncDisruptorAppender.getRingBufferSize().- Returns:
- the size of the ring buffer
-
setQueueSize
Deprecated.useAsyncDisruptorAppender.setRingBufferSize(int)instead.Sets the maximum number of events in the queue.- Parameters:
queueSize- the maximum number of entries in the queue.
-
getSsl
-
setSsl
Set this to non-null to use SSL. See the logback manual for details on how to configure SSL for a client.- Parameters:
sslConfiguration- the SSL configuration
-
getKeepAliveDuration
-
setKeepAliveDuration
If this duration elapses without an event being sent, then thekeepAliveMessagewill be sent to the socket in order to keep the connection alive. Whennull, zero or negative, no keepAlive messages will be sent.- Parameters:
keepAliveDuration- duration between consecutive keep alive messages
-
getKeepAliveMessage
-
setKeepAliveMessage
Message to send for keeping the connection alive ifkeepAliveDurationis non-null and strictly positive. The following values have special meaning:nullor empty string = no keep alive.- "
SYSTEM" = operating system new line (default). - "
UNIX" = unix line ending (\n). - "
WINDOWS" = windows line ending (\r\n).
Any other value will be used as-is.
- Parameters:
keepAliveMessage- the keep alive message
-
isKeepAliveEnabled
public boolean isKeepAliveEnabled() -
isWriteTimeoutEnabled
public boolean isWriteTimeoutEnabled()Whether the write timeout feature is enabled or not.- Returns:
truewhen the appender should try to detect write timeouts,falseotherwise.
-
getKeepAliveCharset
-
setKeepAliveCharset
The charset to use when writing thekeepAliveMessage. Defaults to UTF-8.- Parameters:
keepAliveCharset- charset encoding for the keep alive message
-
setThreadNameFormat
Pattern used by the to set the handler thread name. Defaults to "logback-appender-%1$s-%3$s:%4$d-%2$d"<Event extends DeferredProcessingAware,Listener extends TcpAppenderListener<Event>>. If you change the
AsyncDisruptorAppender.threadFactory, then this value may not be honored.The string is a format pattern understood by
Formatter.format(String, Object...).Formatter.format(String, Object...)is used to construct the actual thread name prefix. The first argument (%1$s) is the string appender name. The second argument (%2$d) is the numerical thread index. The third argument (%3$s) is the string hostname of the currently connected destination. The fourth argument (%4$d) is the numerical port of the currently connected destination. Other arguments can be made available by subclasses.- Overrides:
setThreadNameFormatin classAsyncDisruptorAppender<Event extends DeferredProcessingAware,Listener extends TcpAppenderListener<Event>> - Parameters:
threadNameFormat- thread name format pattern
-
getConnectionStrategy
-
setConnectionStrategy
-
getConnectedDestination
-
getWriteTimeout
-
setWriteTimeout
Sets the time period for which to wait for a write to complete before timing out and attempting to reconnect to that destination. This timeout is used to detect connections where the receiver stops reading.The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout which effectively means "no write timeout".
Note that since a blocking java socket output stream does not have a concept of a write timeout, a task will be scheduled with the same frequency as the write timeout in order to detect stuck writes. It is recommended to use longer write timeouts (e.g. > 30s, or minutes), rather than short write timeouts, so that this task does not execute too frequently. Also, this approach means that it could take up to two times the write timeout before a write timeout is detected.
- Parameters:
writeTimeout- the write timeout
-
AsyncDisruptorAppender.DEFAULT_RING_BUFFER_SIZEinstead