欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ThreadLocal记录日志

程序员文章站 2022-07-03 15:00:44
...
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import trace.visitor.Visitor;

public class Trace {
	private static ThreadLocal<ConcurrentHashMap<Class<? extends ITracer>, ITracer>> tracer = new ThreadLocal<ConcurrentHashMap<Class<? extends ITracer>, ITracer>>() {
		@Override
		protected ConcurrentHashMap<Class<? extends ITracer>, ITracer> initialValue() {
			return new ConcurrentHashMap<Class<? extends ITracer>, ITracer>();
		}
	};
	private static ThreadLocal<Boolean> lock = new ThreadLocal<Boolean>() {
		@Override
		protected Boolean initialValue() {
			return Boolean.FALSE;
		}
	};

	public static boolean isStart() {
		return lock.get();
	}

	public static void start() {
		lock.set(true);
	}

	public static void stop() {
		lock.set(false);
	}

	public static void trace(Visitor visitor, ITraceFilter filter) {

		if (visitor == null) {
			throw new NullPointerException("需要先指定访问者");
		}
		ConcurrentHashMap<Class<? extends ITracer>, ITracer> map = tracer.get();
		for (Map.Entry<Class<? extends ITracer>, ITracer> entry : map
				.entrySet()) {
			ITracer tracer = entry.getValue();
			List<? extends AbstractEntry> entrys = tracer.getEntrySet();
			for (AbstractEntry e : entrys) {
				if (filter == null || filter.accept(e)) {
					e.accept(visitor);
				}
			}
		}

	}

	public static void trace(Visitor visitor) {
		trace(visitor, null);
	}

	public static void reset() {
		ConcurrentHashMap<Class<? extends ITracer>, ITracer> map = tracer.get();
		for (Map.Entry<Class<? extends ITracer>, ITracer> entry : map
				.entrySet()) {
			ITracer tracer = entry.getValue();
			tracer.reset();
		}
	}

	@SuppressWarnings("unchecked")
	public static <T extends ITracer> T getTracer(Class<T> clazz) {
		ConcurrentHashMap<Class<? extends ITracer>, ITracer> map = tracer.get();
		try {
			map.putIfAbsent(clazz, (T) clazz.newInstance());
			return (T) map.get(clazz);
		} catch (Exception e) {
			throw new RuntimeException("无法获取" + clazz.getName() + "的记录器");
		}
	}
}

 

获取一个tracer,调用tracer.debug(×××),记录的东西都保存在ThreadLocal中,最后通过访问者模式暴露给外部使用。可以用来统计方法运行过程中产生的各种日志,以及方法执行的时间,结果等等