slf4j门面模式实现原理

阅读更多
在使用slf4j的时候,只需要通过门面类LoggerFactory类获取Logger
/**
   * Return a logger named according to the name parameter using the statically
   * bound {@link ILoggerFactory} instance.
   *
   * @param name The name of the logger.
   * @return logger
   */
  public static Logger getLogger(String name) {
    ILoggerFactory iLoggerFactory = getILoggerFactory();
    return iLoggerFactory.getLogger(name);
  }

  /**
   * Return a logger named corresponding to the class passed as parameter, using
   * the statically bound {@link ILoggerFactory} instance.
   *
   * @param clazz the returned logger will be named after clazz
   * @return logger
   */
  public static Logger getLogger(Class clazz) {
    return getLogger(clazz.getName());
  }


实际上,这种方式会得调用另外一个类

/**
   * Return the {@link ILoggerFactory} instance in use.
   * 

*

* ILoggerFactory instance is bound with this class at compile time. * * @return the ILoggerFactory instance in use */ public static ILoggerFactory getILoggerFactory() { if (INITIALIZATION_STATE == UNINITIALIZED) { INITIALIZATION_STATE = ONGOING_INITIALIZATION; performInitialization(); } switch (INITIALIZATION_STATE) { case SUCCESSFUL_INITIALIZATION: return StaticLoggerBinder.getSingleton().getLoggerFactory(); case NOP_FALLBACK_INITIALIZATION: return NOP_FALLBACK_FACTORY; case FAILED_INITIALIZATION: throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG); case ONGOING_INITIALIZATION: // support re-entrant behavior. // See also http://bugzilla.slf4j.org/show_bug.cgi?id=106 return TEMP_FACTORY; } throw new IllegalStateException("Unreachable code"); }



注意看的是 return StaticLoggerBinder.getSingleton().getLoggerFactory();

实际上,它真正的方式是通过 org.slf4j.impl.StaticLoggerBinder
,但是,StaticLoggerBinder类在slf4j包中是不存在的。

这实际上就是slf4j的能自动识别实际上的logger日志的原理了。

它调用这个类,这个类,slf4j有一个大概的雏形,但是没有实现,(需要保证slf4j本身编译不报错)。也没有被打包成jar里面,而是由具体的实现该类的,比如log4j等自己实现这个类,并加入具体的jar。那么在实际运行时,就能调用到真实的日志包了。

你可能感兴趣的:(log4j,java)