2012-01-14 192 views
3

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

我按照上SLF4J的网站,一个“T”的指示精神,打造:

  • 是SLF4J在运行时使用绑定到LoggersLoggerFactory
  • 将要使用的记录器适配器A StaticLoggerBinder以“前进” org.slf4j.Logger呼吁到
  • 一个记录器工厂(由静态记录器使用的粘合剂)

夏娃编译很好。我打开它并将其添加到测试项目的lib目录,以及slf4j-api-1.6.2.jar(他们希望我使用的版本)。我在Eclipse中将这两个JAR添加到构建路径中。

我为测试项目创建一个新的运行配置,在运行配置的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"); 
} 

我得到以下运行时错误:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

将所引用的网站,似乎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."); 
     } // ... 

显然,在try块(StaticLoggerBinder.getSingleton())的顶部呼叫投掷NoClassDefFoundError。我只是不明白为什么。

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

是否有额外的步骤,我需要采取Eclipse内部配置类路径?出于某种原因,我的Slf4jBinding.jar是否需要StaticLoggerBinder?我在这里没有想法。提前致谢!

+1

你的StaticLoggerBinder是org.slf4j.impl.StaticLoggerBinder? – 2012-01-14 17:04:00

+2

'虽然不在JAR的根级别,这是什么意思?为了找到你的类必须位于jar中的'/ org/slf4j/impl/StaticLoggerBinder.class'中,如果它位于子文件夹中,它将不会被找到。 – rsp 2012-01-14 17:15:44

回答

4

而不是完全从头开始,然后只适应例如slf4j-simple.jar满足您的需求。所有的绑定代码都在那里,你只需要调整代码来做实际的日志记录。

4

您的jar需要定制实现org.slf4j.impl.StaticLoggerBinder,并且该实现的完全限定类名称必须正好为org.slf4j.impl.StaticLoggerBinder。静态绑定使SLF4J API针对存根版本org.slf4j.impl.StaticLoggerBinder编译,然后在运行时,类加载器将从SLF4J绑定加载真实版本。 SLF4J的每个绑定都有适用于该特定绑定的类org.slf4j.impl.StaticLoggerBinder的不同版本。

0

您可以在您的项目中创建一个org.slf4j.impl包,并在该包中实现一个名为StaticLoggerBinder的类,就像http://javaeenotes.blogspot.com/2011/12/custom-slf4j-logger-adapter.html(我刚刚那样做,它对我来说工作得很好)中所解释的那样。

请注意,您不需要为此构建一个jar文件,只需要在类路径中可以访问org.slf4j.impl.StaticLoggerBinder类(它可以位于jar中,但不是必需的)。