java - 如何在库中配置 sl4j API,同时使客户端可以使用自己的日志记录实现?
问题描述
我目前正在将 Logback 用于库,现在我想更改以使用 sl4j,以便我的库的用户不会被迫使用 Logback。
从我目前阅读的内容来看,在我的配置中我应该有SL4J-api
logback-classic
,所以基本上是这样的:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>{sl4j-api.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>{logback.version}</version>
</dependency>
这意味着在库中我将使用 sl4j API,而实际的记录器实现将是 log4j。
但这也意味着当我的客户使用该库时,log4j jar 也将作为依赖项包含在内。而且我不知道有什么方法可以防止这种情况发生。
我认为使用 sl4j 的目的是防止库的客户端必须处理他们不需要的记录器罐子的情况。但似乎情况并非如此。
这意味着如果他们想改用 log4j,他们仍然必须<exclusion>
在他们的 pom 中编写排除logback-classic
.
或者是否有任何其他方法可以使用 sl4j,以及库 jar 中的特定记录器,并且特定记录器 jar 不包含在客户端所依赖的打包 jar 中。这样客户不需要排除库附带的那些,而只需要插入他们自己的特定记录器?
如果可以做到这一点,配置会是什么样子?
解决方案
You are correct that the purpose of using slf4j in a library is to allow the consumer of the library to choose the logging backend implementation. The way to achieve that is to remove the dependency on logback-classic
from the library. The slf4j-api
dependency provides all of the types required to write log statements, and libraries should not depend on a concrete logging implementation.
If you need to use a logging implementation when running tests, you can specify the dependency with test
scope:
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>{logback.version}</version>
<scope>test</scope>
</dependency>
This will cause Maven to put the dependency on the classpath only when compiling and running tests. Downstream consumers of the library will not inherit a transitive dependency on logback-classic
in this case.
推荐阅读
- nopcommerce - 如何去掉 nop commerce 中按钮旁边的数字
- flask - 当前应用程序未配置 Flask-Mail
- c# - EasyNetQ 等待来自 ISubscriptionResult 的事件
- mysql - 如何在mysql中使用系数数据对用户进行排名?
- flutter - Flutter:数字选择器水平滚动和所选项目始终在中间
- javascript - 导航抽屉遮挡了 Vuetify 工具栏
- python - 如何检查没有。函数的返回值
- ruby-on-rails - 当前页面?关于嵌套资源
- java - 如何通过 post 方法发布 HTTP
- oracle - 哪个 oracle 数据库用户用于创建表、过程、视图、删除它们并插入到表中