在googel上看了一些经验和配置,都不能解决问题,记录此篇文章和经验。
目的,
1.使用Log4j2作为springboot的日志组件
2.记录日志到MongoDB
3.使用Lombok注解,简化代码
配置
1. Maven主要的依赖库
提示:对于Log4j2,spring-data-mongodb-log4j 已经无用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.10.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-nosql</artifactId>
<version>2.9.1</version>
</dependency>
-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-mongodb3</artifactId>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<!-- This is not useful to log4j2
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-log4j</artifactId>
<version>1.10.23.RELEASE</version>
</dependency>
-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
2. 在springboot里面引用Log4j2配置文件,logging.config=classpath:log4j2.xml
Log4j2配置文件中关于使用MongoDB的配置
<NoSql name="mongoAppender" bufferSize="18"><!-- debug日志 -->
<MongoDb3 username="lxiaodao" password="123" databaseName="logdb" collectionName="businesslog" server="localhost" port="27017"/>
</NoSql>
3.使用Lombok的Log4j2注解
@RunWith(SpringRunner.class)
@SpringBootTest
@Log4j2(topic="Inventory_Module")
public class InventoryManagerServiceTest {
@Test
public void test_reduceAmountOfProduct() {
log.info("---------this is reduceAmountOfProduct----------");
log.debug("---------debug test for reduceAmountOfProduct----------");
}
}
什么,你不会安装Lombok,请自行google或者百度。
更多详情可以参考开源代码仓库github:log4j2-mongodb
CSDN同步发布此文章。