Logback DBAppender,以编程方式抛出异常

时间:2013-02-15 13:06:19

标签: logback

我试图以编程方式配置Logback'DBAppender,但不知道哪里出错了。它适用于下面给出的logback.xml配置

<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
    <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">
        <driverClass>com.mysql.jdbc.Driver</driverClass>
        <jdbcUrl>jdbc:mysql://localhost:3306/mydatabase</jdbcUrl>
        <user>myuser</user>
        <password>mypwd</password>
    </connectionSource>
  </appender>

现在我正试图在这样的代码中配置Logger并将其配置为

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

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

        DriverManagerConnectionSource dmcs = new DriverManagerConnectionSource();
        dmcs.setDriverClass("com.mysql.jdbc.Driver");
        dmcs.setUrl("jdbc:mysql://localhost:3306/mydatabase");
        dmcs.setUser("myuser");
        dmcs.setPassword(mypwd);
        dmcs.setContext(lc);

        DBAppender dbapp =  (DBAppender) logger.getAppender("DB");
//it returns an appender with properties in logback.xml file
         if(dbapp != null) {
            dbapp.stop();
            dbapp.setConnectionSource(dmcs);
            dbapp.start();
         }

它抛出异常

java.lang.IllegalStateException: DBAppender cannot function if the JDBC driver does not support getGeneratedKeys method *and* without a specific SQL dialect
    at ch.qos.logback.core.db.DBAppenderBase.start(DBAppenderBase.java:62)
    at ch.qos.logback.classic.db.DBAppender.start(DBAppender.java:96)

没有办法设置方言或setGeneratedKey,我需要做些什么。

2 个答案:

答案 0 :(得分:1)

您还需要启动DriverManagerConnectionSource。

添加行...

dmcs.start();

在启动Appender之前应该这样做。

答案 1 :(得分:1)

我收到此错误(如果JDBC驱动程序不支持没有特定SQL方言的getGeneratedKeys方法,则DBAppender无法运行)

原因是,我为DriverManagerConnectionSource设置了错误的连接URL。不幸的是,logback使我们误以为错误的错误消息