ThreadLocal 仿照日志追踪实现

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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值