需求:實現logback日誌寫入數據庫,並且logback關於數據庫鏈接使用yml已有的數據源信息
在logback.xml改造如下
<!-- 將日誌存儲到oracle數據庫中 -->
<appender name="db-classic-oracle" class="ch.qos.logback.classic.db.DBAppender">
<connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">
</connectionSource>
</appender>
<!-- 日誌輸出級別 -->
<root level="ERROR">
<appender-ref ref="console" />
<appender-ref ref="db-classic-oracle" />
</root>
正常上述appender部分需要設置數據源參數,類似
<url>jdbc:oracle:thin:@XX:1521:orcl</url>
<user>d</user>
<password>111111</password>
但這部分內容實際上應用的主yml已經存在,所以想辦法從yml已有的值去替換。logback本身應該能獲取yml 參數。
類似
<springProperty scope="context" name="dataUrl" source="spring.datasource.username"
defaultValue="localhost"/>
但實驗了很多次,未成功,不知道爲何。所以採取修改DriverManagerConnectionSource源碼的方式去解決。
查看源碼發現下圖設計的源碼存在創建conn 的情況,所以已後面的代碼形式去讀取yml,數據庫連接的相關參數即可。
兩種代碼都能解決。
//讀取yml的方式1
YamlPropertiesFactoryBean yamlMapFactoryBean = new YamlPropertiesFactoryBean();
yamlMapFactoryBean.setResources(new ClassPathResource("application.yml"));
Properties properties = yamlMapFactoryBean.getObject();
String username1=properties.getProperty("spring.datasource.username");
//讀取yml的方式2
ClassPathResource resource = new ClassPathResource("application.yml");
InputStream inputStream = resource.getInputStream();
Map map = null;
Yaml yaml = new Yaml();
map = (Map) yaml.load(inputStream);