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

ThreadLocal 仿照日志追踪实现

程序员文章站 2022-03-05 08:08:17
...
public class ThredLocalUtils {
    private static ThredLocalUtils instance = null;
    private static ThreadLocal<String> tokenObj = new ThreadLocal<String>();
    private ThredLocalUtils(){
        setInstance(this);
    }

    private static void setInstance(ThredLocalUtils instance){
        ThredLocalUtils.instance = instance;
    }

    //初始化标志
    private static final Object obj = new Object();
    private static InheritableThreadLocal<Object> threadFlag = new InheritableThreadLocal<Object>() {
        @Override
        protected Object initialValue() {
            return null;
        }
    };

    //当前线程的UUID信息,用于日志追踪
    private static InheritableThreadLocal<String> currLogUuid = new InheritableThreadLocal<String>() {
        @Override
        protected String initialValue() {
            return UUID.randomUUID().toString();
        }
    };

    //日志清理
    public static void clear(){
        currLogUuid.remove();
        threadFlag.remove();
        tokenObj.remove();
    }

    public static String getCurrLogUuid(){
        if(!isInit()){
            throw new IllegalArgumentException("TLS未初始化");
        }
        return currLogUuid.get()+getTokenId();
    }

    private static String getTokenId() {
        return tokenObj.get()==null?"":tokenObj.get();
    }

    public static String getLogPrefix(){
        if(!isInit()){
            ThredLocalUtils.isInit();
        }
        return "<uuid="+getCurrLogUuid()+">";
    }

    private static boolean isInit() {

        return threadFlag.get()!=null;
    }

    private static boolean isSetToken(){
        return tokenObj.get() !=null;
    }

    public static boolean initialize(String tokeId){
        if(!isSetToken()){
            tokenObj.set(tokeId);
        }
        if(isInit()){
            return false;
        }
        threadFlag.set(obj);
        return true;
    }

    public static boolean initialize(){
        if(isInit()){
            return false;
        }
        threadFlag.set(obj);
        return true;
    }

    public static void setTokenId(String tokenId){
        tokenObj.set(tokenId);
    }

    public static void main(String[] args) {
        ThredLocalUtils.initialize();
        System.out.println("日志初始化 "+ThredLocalUtils.getLogPrefix());
        System.out.println("日志追踪1 "+ThredLocalUtils.getLogPrefix());
        System.out.println("日志追踪2 "+ThredLocalUtils.getLogPrefix());
        System.out.println("日志追踪3 "+ThredLocalUtils.getLogPrefix());
        System.out.println("日志结束 "+ThredLocalUtils.getLogPrefix());
        ThredLocalUtils.clear();
    }
}
相关标签: java java