When not to use AsyncAppender in logback by default

我的未来我决定 提交于 2020-01-01 08:26:24

问题


Logback supports using an async appender with the class ch.qos.Logback.classic.AsyncAppender and according to the documentation, this will reduce the logging overhead on the application. So, why not just make it the default out of the box. What usecases are better served by using a sync appender. One problem I can see with the Async appender is that the log messages will not be chronological. Are there any other such limitations?


回答1:


The AsyncAppender acts as a dispatcher to another appender. It buffers log events and dispatches them to, say, a FileAppender or a ConsoleAppender etc.

  • Why use the AsyncAppender?

    • The AsyncAppender buffers log events, allowing your application code to move on rather than wait for the logging sub system to complete a write. This can improve your application's responsiveness in cases where the underying appender is slow to respond e.g. a database or a file system which may be prone to contention.
  • Why not make it the default behaviour?

    • The AsyncAppender cannot write to a file or console or a database or a socket etc. Instead, it just delegates log events to an appender which can do that. Without the underlying appender the AsyncAppender is, effectively, a no-op.
    • The buffer of log events sits on your application's heap; this is a potential resource leak. If the buffer builds more quickly than it can be drained then the buffer will consume resources which your application might want to use.
    • The AsyncAppender's need for configuration to balance the competing demands of no-loss and resource leakage and to handle on-shutdown draining of its buffer means that it is more complicated to manage and to reason about than simply using synchronous writes. So, on the basis of preferring simplicity over complexity it makes sense for Logback's default write strategy to be synchronous.

The AsyncAppender exposes configuration levers which you can use to address the potential resource leakage. For example:

  • You can increase the buffer capacity
  • You can instruct Logback to drop events once the buffer reaches maximum capcacity
  • You can control what types of events are discarded; drop TRACE events before ERROR events etc

The AsyncAppender also exposes configuration levers which you can use to limit (though not eliminate) the loss of events during application shutdown.

However, it remains true that the simplest safest way of ensuring that log events are successfully writtten is to write them synchronously. The AsyncAppender should only be considered when you have a proven issue where writing to an appender materially affects your application responsiveness / throughput.



来源:https://stackoverflow.com/questions/47372092/when-not-to-use-asyncappender-in-logback-by-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!