SLF4J自定义绑定不起作用

IAm*_*aja 3 java eclipse classpath slf4j

我们花了很多时间开发自己的自定义日志记录系统(对或错,这就是高层决定的!)我被要求编写自定义SLF4J绑定(API实现)以便我们的许多SLF4J利用组件(例如Apache Camel)将开始记录到我们新的本地系统.

我按照SLF4J网站上的说明操作了"T",创建:

  • 一个StaticLoggerBinder是SLF4J使用在运行时绑定LoggersLoggerFactory
  • 一个记录器适配器,用于"转发" org.slf4j.Logger呼叫
  • 记录器工厂(由静态记录器绑定器使用)

一切都很好.我将它装罐并将其添加到lib测试项目的目录中,以及slf4j-api-1.6.2.jar(他们希望我使用的版本).我在Eclipse中的构建路径中添加了两个JAR.

我为测试项目创建了一个新的运行配置,在Run Configuration的Classpath选项卡窗格中,我看到它有User Entries >> TestBinding >> Slf4jBinding.jar and slf4j-api-1.6.2.jar.

因此,似乎两个JAR都在Run Configuration的类路径中.

在项目中运行看起来像这样的驱动程序:

public static void main(String[] args) {
    Logger logger = LoggerFactory.getLogger(TestDriver.class);
    logger.error("Test");
}
Run Code Online (Sandbox Code Playgroud)

我得到以下运行时错误:

SLF4J:无法加载类"org.slf4j.impl.StaticLoggerBinder".SLF4J:默认为无操作(NOP)记录器实现SLF4J:有关更多详细信息,请参阅http://www.slf4j.org/codes.html#StaticLoggerBinder.

去那个被引用的网站,似乎SLF4J找不到我StaticLoggerBinder在类路径上Slf4jBinding.jar,虽然不是在JAR的根级别.

我查看了SLF4J的LoggerFactory.java源文件,发现抛出此类错误的代码:

private final static void bind() {
    try {
        // the next line does the binding
        StaticLoggerBinder.getSingleton();
        INITIALIZATION_STATE = SUCCESSFUL_INITILIZATION;
        emitSubstituteLoggerWarning();
    } catch (NoClassDefFoundError ncde) {
        String msg = ncde.getMessage();
        if (messageContainsOrgSlf4jImplStaticLoggerBinder(msg)) {
            INITIALIZATION_STATE = NOP_FALLBACK_INITILIZATION;
            Util
            .report("Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".");
            Util.report("Defaulting to no-operation (NOP) logger implementation");
            Util.report("See " + NO_STATICLOGGERBINDER_URL
            + " for further details.");
        } // ...
Run Code Online (Sandbox Code Playgroud)

很明显,try块(StaticLoggerBinder.getSingleton())顶部的调用正在抛出NoClassDefFoundError.我只是不明白为什么.

我选择不在此处粘贴代码,因为我认为这只是一个类路径问题.在我能够通过此问题之前,我的代码是否正确遵守SLF4J的绑定策略仍然是未知的.

我需要在Eclipse中配置类路径吗?出于某种原因,我的Slf4jBinding.jar需要能否StaticLoggerBinder在其根源内?我在这里没有想法.提前致谢!

Dev*_*Dev 5

您的jar需要自定义实现, org.slf4j.impl.StaticLoggerBinder并且该实现的完全限定类名必须是完全正确的org.slf4j.impl.StaticLoggerBinder.静态绑定的工作原理是根据存根版本编译SLF4J API org.slf4j.impl.StaticLoggerBinder,然后在运行时,类加载器将从SLF4J绑定加载实际版本.SLF4J的每个绑定具有org.slf4j.impl.StaticLoggerBinder适合于该特定绑定的类的不同版本.