Log接口的重新封装

时间:2023-03-09 21:27:56
Log接口的重新封装

闲来没事,看见当前的项目的日志形式有点冗余,每个类都需要声明确实有点繁琐,

因此重新将logback重新封装一下,供整个工程共享使用,版本是1.0.9。

代码如下:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import org.slf4j.Marker;
import ch.qos.logback.classic.Level;
public final class Logger { private static ch.qos.logback.classic.Logger innerLogger; private static final String FQCN = Logger.class.getName(); private static Method innerMethod; public static int load(ch.qos.logback.classic.Logger logger) {
innerLogger = logger;
try {
innerMethod = innerLogger.getClass().getDeclaredMethod("filterAndLog_0_Or3Plus", String.class, Marker.class, Level.class, String.class, Object[].class, Throwable.class);
innerMethod.setAccessible(true);
} catch (NoSuchMethodException | SecurityException e) {
innerLogger.error("load failed, Exception:" + e);
return -;
}
return ;
} public static void debug(String msg) {
innerLogMethod(FQCN, null, Level.DEBUG, msg, null, null);
} public static void error(String msg) {
innerLogMethod(FQCN, null, Level.ERROR, msg, null, null);
} public static void info(String msg) {
innerLogMethod(FQCN, null, Level.INFO, msg, null, null);
} public static void warn(String msg) {
innerLogMethod(FQCN, null, Level.WARN, msg, null, null);
} private static void innerLogMethod(String localFQCN, Marker marker, Level level, String msg, Object[] params, Throwable t)
{
try {
innerMethod.invoke(innerLogger, localFQCN, marker, level, msg, params, t);
} catch (SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
innerLogger.error("execute innerMethod failed, Exception:" + e);
}
}
}

详细原理随后再解释吧: