JimmyD
JimmyD

Reputation: 2759

Logback does not close datasource connection of dbappender

We are using Logback 1.1.7 for one of our web application (hosted on Tomcat 8). When we stop the web applicatin using the Tomcat manager the dataconnection of our DBappender is not closed. We need to restart the full Tomcat service to release the database connection of Logback.

The Tomcat connection pool is used for managing the connections to the database.

We use the xml file for configuring the appenders and looks like:

    <?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
        <connectionSource class="ch.qos.logback.core.db.JNDIConnectionSource">
            <jndiLocation>java:comp/env/jdbc/database</jndiLocation>
        </connectionSource>
    </appender>

    <root level="ALL">
        <appender-ref ref="DB" />
    </root>

</configuration>

In the code we are calling the logger by:

Logger logger = LoggerFactory.getLogger("defaultLogger");

Is there any way we can manually close the connection of Logback when we are stopping the application?

Upvotes: 2

Views: 557

Answers (1)

ideano1
ideano1

Reputation: 150

Add <shutdownhook> in your configuration which you can either manually or automatically close all the connections and also flush all async logging.

Logback configuration :

<configuration>
   <!-- in the absence of the class attribute, assume 
   ch.qos.logback.core.hook.DelayingShutdownHook -->
   <shutdownHook/>
  .... 
</configuration>

And you can call

org.apache.log4j.LogManager.shutdown();

Here is the sample code :

import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.LoggerContext;

...

ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
// Check for logback implementation of slf4j
if (loggerFactory instanceof LoggerContext) {
    LoggerContext context = (LoggerContext) loggerFactory;
    context.stop();
}

Upvotes: 1

Related Questions