Search code examples
java-8logback

Set sqldialect to logback db appender programmatically


I'm writing source code for creating DBAppender to use the datasource of my connection pool. Now when I start the DBAppender I get the error "DBAppender cannot function if the JDBC driver does not support getGeneratedKeys method and without a specific SQL dialect". So I want to add the sqlDialect to my implementation but cannot find a way to do this.

The code for adding the appender to the logger looks like:

LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

DataSourceConnectionSource source = new DataSourceConnectionSource();

source.setDataSource(Database.getInstance().getDatasource());

DBAppender dbAppender = new DBAppender();
dbAppender.setName("db");
dbAppender.setConnectionSource(source);
dbAppender.setContext(lc);      
dbAppender.start();

Logger logger = (Logger) LoggerFactory.getLogger(Loggerutils.class);
logger.addAppender(dbAppender);
logger.setLevel(Level.DEBUG);

When I check another project that using Logback I used <sqlDialect class="ch.qos.logback.core.db.dialect.MsSQLDialect" /> in my xml configuration.

Is there a way to add the sqlDialect in my implementation of the appender?


Solution

  • You should start your connection source after you've set your data source.

        source.setDataSource(Database.getInstance().getDatasource());
        source.start()
    

    This calls the discoverConnectionProperties() method where the dialect is determined by the driver of your data source.

    source