logback.xml日志写入数据库改造,重写源码手工读取yml参数作为数据源参数的方法
需求:实现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); 相关推荐
瓜牛呱呱 2020-11-12
柳木木的IT 2020-11-04
yifouhu 2020-11-02
lei0 2020-11-02
源码zanqunet 2020-10-26
码代码的陈同学 2020-10-14
lukezhong 2020-10-14
clh0 2020-09-18
changcongying 2020-09-17
星辰大海的路上 2020-09-13
abfdada 2020-08-26
mzy000 2020-08-24
shenlanse 2020-08-18
zhujiangtaotaise 2020-08-18
xiemanR 2020-08-17