Search code examples
javalogginglogbackslf4j

ThreadLocal guard in Logback appender base classes


ThreadLocal guard is utilized in doAppend method of Logback base appenders to prevent calling back on itself.

Under what circumstances would doAppend call back on itself?


Solution

  • Under what circumstances would doAppend call back on itself?

    Anytime the Appender::append creates logging events that feedback into the appender itself. This is any Appender makes method calls against a 3rd party library which in itself uses a logging framework that uses slf4j or can be bridged to logback/slf4j.

    Take the SMTPAppender as an example. Per the docs:

    The SMTPAppender relies on the JavaMail API.

    If the following statements are true then you have a feedback loop:

    1. An ancestor of the JavaMail logger namespace has an attached SMTPAppender, say the root logger for example.
    2. JavaMail session debugging has been enabled which will generate JUL log records on SMTP send.
    3. The sl4fj JUL bridge handler is installed and is redirecting the JUL log records to the already attached SMTPAppender in point 1.
    4. There is a running thread that tries to generate the first log message.
    5. The SMTPAppender attempts to send email message. This action will generate more messages that feedback into logger in point 1.

    When all of this is true, your application log message that you wanted to send via email ended up creating X number of log message debug statements from JavaMail. Those X number of message now end up calling SMTPAppender::append and so on.

    This same type of example could be applied to the DBAppender which requires a JDBC driver that could be directly logging to slf4j. Same rules for any custom appenders applies here too.

    In general, you don't what your application logs to be mixed with this appender generated log information or create some sort of feedback loop that takes down your server.