The log of logback.xml is written to the database, and the method of rewriting the source code to read the yml parameter manually as the data source parameter

Requirements: realize logback log writing to database, and logback uses existing data source information of yml for database link
The transformation in logback.xml is as follows

<!-- Store logs to oracle Database -->
    <appender name="db-classic-oracle" class="ch.qos.logback.classic.db.DBAppender"> 
            <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">
     <!-- Log output level -->
    <root level="ERROR">
        <appender-ref ref="console" />
        <appender-ref ref="db-classic-oracle" />

Normally, the data source parameters need to be set in the above appender part, similar to


But in fact, the main yml applied in this part already exists, so we try to replace it with the existing value of yml. logback itself should be able to get the yml parameter.

 <springProperty scope="context" name="dataUrl" source="spring.datasource.username"

However, many experiments were carried out without success, and I don't know why. So we need to modify the source code of DriverManagerConnectionSource to solve this problem.

Check the source code and find that the source code in the figure below creates conn, so read the yml in the later code form and the relevant parameters of database connection.
Both codes can be solved.

//Method 1 of reading yml
            YamlPropertiesFactoryBean yamlMapFactoryBean = new YamlPropertiesFactoryBean();
            yamlMapFactoryBean.setResources(new ClassPathResource("application.yml"));
            Properties properties = yamlMapFactoryBean.getObject();
            String username1=properties.getProperty("spring.datasource.username");
            //Method 2 of reading yml
            ClassPathResource resource = new ClassPathResource("application.yml");
            InputStream inputStream = resource.getInputStream();
            Map map = null;
            Yaml yaml = new Yaml();
            map = (Map) yaml.load(inputStream);

Tags: Java Database Oracle Spring xml

Posted on Sat, 30 Nov 2019 20:53:12 -0800 by dape2009