乐趣区

关于java:ObjectiveSQL-扩展之-自定义Logger-Framework

目前,比拟风行的 Log Framework 有:Apache Commons Logging,Avalon LogKit,log4j,SLF4J 等,ObjectiveSQL 无奈确定利用零碎应用哪一种 Log Framework,所以提供了扩大接口,由利用零碎依据本身的须要进行实现,以 Slf4j 为示例,具体介绍利用零碎如何扩大实现 Log Framework。

ObjectiveSQL 中的扩大接口 Logger.java 和 LoggerFactory.java 如下:

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 示例如下:

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。

退出移动版