目前,比較流行的Log Framework 有:Apache Commons Logging,Avalon LogKit,log4j,SLF4J 等,ObjectiveSQL 沒法肯定應用系統使用哪種 Log Framework,因此提供了擴展接口,由應用系統根據自身的須要進行實現,以Slf4j 爲示例,詳細介紹應用系統如何擴展實現Log Framework。java
ObjectiveSQL 中的擴展接口Logger.java 和LoggerFactory.java 以下:git
public interface Logger { void debug(long elapsedTime, String sql, Object[] params); void info(long elapsedTime, String sql, Object[] params); void error(String message, Throwable throwable); }
public interface LoggerFactory { Logger create(Class<?> clazz); }
結合SpringBoot 示例以下:github
import com.github.braisdom.objsql.Logger; import com.github.braisdom.objsql.LoggerFactory; import com.github.braisdom.objsql.util.StringUtil; import java.util.Arrays; public class ObjLoggerFactoryImpl implements LoggerFactory { private class ObjLoggerImpl implements Logger { private final org.slf4j.Logger logger; public ObjLoggerImpl(org.slf4j.Logger logger) { this.logger = logger; } @Override public void debug(long elapsedTime, String sql, Object[] params) { logger.debug(createLogContent(elapsedTime, sql, params)); } @Override public void info(long elapsedTime, String sql, Object[] params) { logger.info(createLogContent(elapsedTime, sql, params)); } @Override public void error(String message, Throwable throwable) { logger.error(message, throwable); } private String createLogContent(long elapsedTime, String sql, Object[] params) { String[] paramStrings = Arrays.stream(params).map(param -> String.valueOf(param)).toArray(String[]::new); String paramString = String.join(",", paramStrings); return String.format("[%dms] %s, with: [%s]", elapsedTime, sql, String.join(",", paramString.length() > 100 ? StringUtil.truncate(paramString, 99) : paramString)); } } @Override public Logger create(Class<?> clazz) { org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(clazz); return new ObjLoggerImpl(logger); } }
LoggerFactory loggerFactory = new ObjLoggerFactoryImpl(); Databases.installLoggerFactory(loggerFactory);
其實,原理很簡單,只須要按要求實現Logger 和LoggerFactory 兩個接口,在接口中注入自身Log Framework 的實現便可,示例中是以Slf4j 爲示例,其它類型的Framework 也相似。完成具體實現後,須要將實例注入ObjectiveSQL。spring