Spring Boot Logback DB Appender属性

时间:2015-10-17 12:34:13

标签: java spring logback

您好我想在Spring Boot应用程序中使用DBAppender。我想从application.properties文件中检索数据库连接属性。然而,它似乎并没有认识到它们。 请注意,我使用的是Spring Boot 1.2.x,因此我暂时无法使用logback-spring.xml

我使用的配置如下:

<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
        <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">

            <driverClass>${spring.datasource.driver-class-name}</driverClass>
            <url>${spring.datasource.url}</url>
            <user>${spring.datasource.username}</user>
            <password>${spring.datasource.password}</password>
        </connectionSource>
    </appender>

3 个答案:

答案 0 :(得分:4)

在搜索类似的解决方案时偶然发现了这一点。由于这仍然没有答案,我发现了一些方法:

1)如果你使用的是Spring Boot 1.3+(你已经指出你不是为了将来参考),我设法使用&lt; springProperty&gt; 标签来重用它来自application.properties的值。

application.properties(用于嵌入式H2 DB):

spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=

的logback-spring.xml:

<springProperty name="spring.datasource.driverClassName" source="spring.datasource.driverClassName"/>
<springProperty name="spring.datasource.url" source="spring.datasource.url"/>
<springProperty name="spring.datasource.username" source="spring.datasource.username"/>
<springProperty name="spring.datasource.password" source="spring.datasource.password"/>

<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
    <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">
        <driverClass>${spring.datasource.driverClassName}</driverClass>
        <url>${spring.datasource.url}</url>
        <user>${spring.datasource.username}</user>
        <password>${spring.datasource.password}</password>
    </connectionSource>
</appender>

2)将应用程序属性导入为属性源:Unable to use Spring Property Placeholders in logback.xml

<property resource="application.properties" />

3)也许您能够在容器JNDI中注册数据源并使用logback的JNDIConnectionSource代替?看看这篇文章:How to create JNDI context in Spring Boot with Embedded Tomcat Container

答案 1 :(得分:1)

因此,请支持jpt的答案。 因为没有“

  

<property resource="application.yml" />

”(或该答案中的.properties),我什么都不会工作。

但是我的回答和贡献:我想添加它也可以与application.yml一起使用。

我将尝试列出我在这里所做的所有事情:

设置3个环境变量。

SPRING_DATASOURCE_URL
SPRING_DATASOURCE_USER
SPRING_DATASOURCE_PASSWORD

application.yml的内容(如下)

spring:
  datasource:
    #SPRING_DATASOURCE_URL environment variable will be something like -> jdbc:sqlserver://MySqlServer\\MyInstance:1433;DatabaseName=MyDbName;
    url: ${SPRING_DATASOURCE_URL}
    username: ${SPRING_DATASOURCE_USERNAME}
    password: ${SPRING_DATASOURCE_PASSWORD}
    driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
logging:
    config: classpath:logback-spring.xml

注意,我正在使用文件“ logback-spring.xml”。我不确定是否会有所作为(相对于仅使用“ logback.xml”)

logback-spring.xml的内容(如下)

<configuration debug="true" scan="true" scanPeriod="30 seconds">


    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} [%file:%line] %msg%n</pattern>
        </encoder>
    </appender>



    <!-- THIS IS THE MAGIC LINE that JPT figured out -->
    <property resource="application.yml" />

    <springProperty name="humptydumptyurl" source="spring.datasource.url"/>
    <springProperty name="humptydumptyusername" source="spring.datasource.username"/>
    <springProperty name="humptydumptypassword" source="spring.datasource.password"/>


    <appender name = "MyDbAppender" class="ch.qos.logback.classic.db.DBAppender">
        <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">
            <driverClass>com.microsoft.sqlserver.jdbc.SQLServerDriver</driverClass>
            <url>${humptydumptyurl}</url>
            <user>${humptydumptyusername}</user>
            <password>${humptydumptypassword}</password>
        </connectionSource>
    </appender>



    <root level="INFO">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="MyDbAppender"/>
    </root>

</configuration>

注意,我故意使用“ humptydumpty”以避免歧义。您可能会使用更好的前缀,但我想显示映射的左侧可以是您想要的任何名称。

注意,我的application.properties文件为空。我是100%application.yml。

注意,您还可以设置/使用第四个环境变量(我认为它可以工作,但我尚未测试)

  

SPRING_DATASOURCE_DRIVER-CLASS-NAME

及其两个好友

datasource:
    driverClassName: ${SPRING_DATASOURCE_DRIVER-CLASS-NAME}

  <springProperty name="humptydumptydriverclassname" source="spring.datasource.driver-class-name"/>

......

下面的一些mssql-server注释(对大多数用户来说可能并不重要)

我用过

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>7.0.0.jre8</version>
        </dependency>

并使其正常工作。

我必须对DDL进行一些调整,因为在INSERT上出现“截断”错误。

-- This SQL script creates the required tables by ch.qos.logback.classic.db.DBAppender
-- 
-- The event_id column type was recently changed from INT to DECIMAL(40)
-- without testing.

DROP TABLE logging_event_property 
DROP TABLE logging_event_exception 
DROP TABLE logging_event 

CREATE TABLE logging_event 
  ( 
    timestmp         DECIMAL(20) NOT NULL,
    formatted_message  VARCHAR(max) NOT NULL,
    logger_name       VARCHAR(512) NOT NULL,
    level_string      VARCHAR(512) NOT NULL,
    thread_name       VARCHAR(512),
    reference_flag    SMALLINT,
    arg0              VARCHAR(512),
    arg1              VARCHAR(512),
    arg2              VARCHAR(512),
    arg3              VARCHAR(512),
    caller_filename   VARCHAR(512) NOT NULL,
    caller_class      VARCHAR(512) NOT NULL,
    caller_method     VARCHAR(512) NOT NULL,
    caller_line       CHAR(16) NOT NULL,
    event_id          DECIMAL(38) NOT NULL identity,
    PRIMARY KEY(event_id) 
  ) 

CREATE TABLE logging_event_property 
  ( 
    event_id          DECIMAL(38) NOT NULL, 
    mapped_key        VARCHAR(512) NOT NULL, 
    mapped_value      VARCHAR(1024), 
    PRIMARY KEY(event_id, mapped_key), 
    FOREIGN KEY (event_id) REFERENCES logging_event(event_id) 
  ) 

CREATE TABLE logging_event_exception 
  ( 
    event_id         DECIMAL(38) NOT NULL, 
    i                SMALLINT NOT NULL, 
    trace_line       VARCHAR(512) NOT NULL, 
    PRIMARY KEY(event_id, i), 
    FOREIGN KEY (event_id) REFERENCES logging_event(event_id) 
  ) 

最后,让我给出所有最重要的调试提示。

首先将连接字符串值硬编码,使其正常工作...开始插入环境变量替换项时。

ch.qos.logback.classic.db.DBAppender必须具有良好且有效的连接字符串以进行“检查” .....如果输入错误的连接字符串,则会出现此类错误(下面)。我花了4个小时来追查错误,这是因为追逐下面的错误,仅仅是因为我的连接字符串无法正常工作。再次,先将正确/有效的值硬编码到logback-spring.xml中,使其生效,然后回圈并执行环境变量spring-properties替换伏都教。

因此对于db-appender,首先硬编码您的url,用户名,密码,使其正常工作,然后慢慢开始进行替换...我在没有意识到所有替换之前就追赶了以下错误方式工作。...

06:19:09,721 |-WARN in ch.qos.logback.classic.db.DBAppender[MyDbAppender] - Attempted to append to non started appender [MyDbAppender].
    at org.springframework.boot.context.logging.LoggingApplicationListener.onApplicationEvent(LoggingApplicationListener.java:202)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:127)
    at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:75)
    at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:54)
    at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:347)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:306)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
Caused by: java.lang.IllegalStateException: Logback configuration error detected: 
ERROR in ch.qos.logback.core.joran.spi.Interpreter@68:16 - RuntimeException in Action for tag [appender] java.lang.IllegalStateException: DBAppender cannot function if the JDBC driver does not support getGeneratedKeys method *and* without a specific SQL dialect
    at org.springframework.boot.logging.logback.LogbackLoggingSystem.loadConfiguration(LogbackLoggingSystem.java:169)
    at org.springframework.boot.logging.AbstractLoggingSystem.initializeWithSpecificConfig(AbstractLoggingSystem.java:67)
    at org.springframework.boot.logging.AbstractLoggingSystem.initialize(AbstractLoggingSystem.java:57)
    at org.springframework.boot.logging.logback.LogbackLoggingSystem.initialize(LogbackLoggingSystem.java:117)
    at org.springframework.boot.context.logging.LoggingApplicationListener.initializeSystem(LoggingApplicationListener.java:298)

最后只是列出所有内容。

这些是我使用的登录版本:

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>

答案 2 :(得分:0)

我之前一直在寻找解决方案 jpt 和特别是 granadaCoder 之前描述的,但尽管与 logback-spring.xml 一起工作,但它对我不起作用。相反,更简单的方法有所帮助:

魔线

<property resource="application-local.yml" />

然后简单

<appender name="DB_Logger" class="ch.qos.logback.classic.db.DBAppender">
            <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">
                <driverClass>com.mysql.cj.jdbc.Driver</driverClass>
                <url>${URL}</url>
                <user>${USERNAME}</user>
                <password>${PASSWORD}</password>
            </connectionSource>
        </appender>

显然在我的 application.yml 中有 spring.datasource.URL/USERNAME/PASSWORD