LogFactory 日志工厂
日志组件: 主要使用的工厂设计模式、适配器设计模式
包目录
mybaits为了兼容其他第三方组件,自己定义一个针对于mybaits的通用接口
public interface Log {
boolean isDebugEnabled();
boolean isTraceEnabled();
void error(String s, Throwable e);
void error(String s);
void debug(String s);
void trace(String s);
void warn(String s);
}
顺序加载
static {
// 第一步: 加载slf4f
tryImplementation(LogFactory::useSlf4jLogging);
// 第二步: commonLogging
tryImplementation(LogFactory::useCommonsLogging);
// 第三步 log4f2
tryImplementation(LogFactory::useLog4J2Logging);
tryImplementation(LogFactory::useLog4JLogging);
tryImplementation(LogFactory::useJdkLogging);
tryImplementation(LogFactory::useNoLogging);
}
如果当前类下有就加载。
myabtis 如果当前类下面无法找到该组件应该怎么办
tryImplementation(LogFactory::useSlf4jLogging);
看一个简单源码日志分析
public static synchronized void useSlf4jLogging() {
setImplementation(org.apache.ibatis.logging.slf4j.Slf4jImpl.class);
}
private static void setImplementation(Class<? extends Log> implClass) {
try {
Constructor<? extends Log> candidate = implClass.getConstructor(String.class);
Log log = candidate.newInstance(LogFactory.class.getName());
if (log.isDebugEnabled()) {
log.debug("Logging initialized using '" + implClass + "' adapter.");
}
logConstructor = candidate;
} catch (Throwable t) {
throw new LogException("Error setting Log implementation. Cause: " + t, t);
}
}
private static void tryImplementation(Runnable runnable) {
// 判断是否为null 如果为null 加载类 如果不为null 就不加载。
if (logConstructor == null) {
try {
//然后运行该对象
runnable.run();
} catch (Throwable t) {
// ignore
}
}
}
这样做的目前就是在当前类下面如果没有找到继续加载下一个 ( ignore)了异常。