日志收集器

一款简易的日志收集器,可以记录上下文,及收集时间打点。


public class LogContext {

    private static final String LOG_CATEGORY = "LOG_CATEGORY";

    private static ThreadLocal<Map<String, String>> CONTEXT = new ThreadLocal();
    private static ThreadLocal<Map<String, LocalDateTime>> TIME_MARK = new ThreadLocal();

    public static void init() {
        clear();
        CONTEXT.set(Maps.newLinkedHashMap());
        TIME_MARK.set(Maps.newLinkedHashMap());
    }

    public static void clear() {
        CONTEXT.remove();
        TIME_MARK.remove();
    }

    public static void category(String logCategory) {
        put(LOG_CATEGORY, logCategory);
    }

    public static void put(String key, String value) {
        if (Objects.isNull(CONTEXT.get())) {
            CONTEXT.set(Maps.newLinkedHashMap());
        }
        CONTEXT.get().put(key, value);
    }

    public static void mark(String key) {
        if (Objects.isNull(TIME_MARK.get())) {
            TIME_MARK.set(Maps.newLinkedHashMap());
        }
        TIME_MARK.get().put(key, LocalDateTime.now());
    }

    public static String logContent() {
        StringBuilder s = new StringBuilder();

        Map<String, String> contextMap = CONTEXT.get();
        if (!CollectionUtils.isEmpty(contextMap)) {
            contextMap.forEach((k, v) -> s.append(String.format(" %s=%s,", k, v)));
            s.deleteCharAt(s.length() - 1);
        }

        Map<String, LocalDateTime> timeMarkMap = TIME_MARK.get();
        if (!CollectionUtils.isEmpty(timeMarkMap)) {
            if (s.length() != 0) {
                s.append(" |");
            }
            List<Map.Entry<String, LocalDateTime>> timeMarkList = new ArrayList(timeMarkMap.entrySet());
            for (int i = 0; i < timeMarkList.size() - 1; i++) {
                Map.Entry<String, LocalDateTime> thisTime = timeMarkList.get(i);
                Map.Entry<String, LocalDateTime> nextTime = timeMarkList.get(i + 1);
                long duration = Duration.between(thisTime.getValue(), nextTime.getValue()).toMillis();
                s.append(String.format(" %s=%d,", thisTime.getKey(), duration));
            }
            Map.Entry<String, LocalDateTime> lastTime = timeMarkList.get(timeMarkList.size() - 1);
            long duration = Duration.between(lastTime.getValue(), LocalDateTime.now()).toMillis();
            s.append(String.format(" %s=%d", lastTime.getKey(), duration));
        }

        return s.toString();
    }

    public static void log() {
        logger.info(logContent());
    }

}

你可能感兴趣的:(Java,java,jvm)