java-日志框架
一需求材料 1 common-logging 2 jcl-over-slf4j 3 slf4j-api 4 logback-classic. 5 spring-beans.4.15. 二 简单流程 org.springframework.web.context.ContextLoader.initWebApplicationContext -275 org.apache.commons.logging.Log logger = org.apache.commons.logging.LogFactory.getLog(ContextLoader.class) org.apache.commons.logging.LogFactory.getFactory() org.apache.commons.logging.LogFactory.getCachedFactory() org.apache.commons.logging.LogFactory.getConfigurationFile() org.apache.commons.logging.LogFactory.getSystemProperty() org.apache.commons.logging.LogFactory..getResourceAsStream() org.apache.commons.logging.LogFactory.cacheFactory() org.apache.commons.logging.impl.SLF4JLogFactory.getInstance( org.slf4j,Logger slf4jLogger = org.slf4j.LoggerFactory.getLogger( org.slf4j.ILoggerFactory iLoggerFactory = org.slf4j.LoggerFactory.getILoggerFactory( org.slf4j.LoggerFactory.performInitialization( org.slf4j.LoggerFactory.bind( org.slf4j.LoggerFactory.findPossibleStaticLoggerBinderPathSet() org.slf4j.LoggerFactory.reportMultipleBindingAmbiguity() StaticLoggerBinder.getSingleton(); reportActualBinding(staticLoggerBinderPathSet); emitSubstituteLoggerWarning ) ) return org.slf4j.impl.StaticLoggerBinder.getSingleton().getLoggerFactory(); ); ); org.apache.commons.logging.Log newInstance = new org.apache.commons.logging.impl.SLF4JLocationAwareLog((LocationAwareLogger) slf4jLogger); ) 三 核心API common-logging.jar (I)org.apache.commons.logging.Log (A)org.apache.commons.logging.LogFactory jcl-over-logging.jar (C)org.apache.commons.logging.impl.SLF4JLogFactory extends org.apache.commons.logging.LogFactory (C)org.apache.commons.logging.impl.SLF4JLocationAwareLog implements org.apache.commons.logging.Log slf4j-api.jar (I)org.slf4j.Logger (C)org.slf4j.LoggerFactory (I)org.slf4j.ILoggerFactory (I)org.slf4j.spi.LocationAwareLogger extends org.slf4j.Logger logback-classic.jar (C)ch.qos.logback.classic.LoggerContext extends ContextBase implements org.slf4j.ILoggerFactory (C)org.slf4j.impl.StaticLoggerBinder implements org.slf4j.spi.LoggerFactoryBinder
(罗嗦话)
正如我之前说的,在你的代码中使用SLF4J写日志语句的主要出发点是使得你的程序独立于任何特定的日志类库,依赖于特定类库可能需要使用不同于你已有的配置,并且导致更多维护的麻烦。除此之外,还有一个SLF4J API的特性是使得我坚持使用SLF4J而抛弃我长期间钟爱的Log4j的理由,是被称为占位符(place holder),在代码中表示为“{}
”的特性。占位符是一个非常类似于在String
的format()
方法中的%s
,因为它会在运行时被某个提供的实际字符串所替换。这不仅降低了你代码中字符串连接次数,而且还节省了新建的String对象。通过使用SLF4J,你可以在运行时延迟字符串的建立,这意味着只有需要的String对象才被建立。而如果你已经使用log4j,那么你已经对于在if条件中使用debug语句这种变通方案十分熟悉了,但SLF4J的占位符就比这个好用得多。