package org.jeecg.config.aop.logprint;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.ttl.TransmittableThreadLocal;

/**
 * @description: 使用ttl 实现日志收集
 * @author: niugeng
 * @create: 2023-03-20 09:59
 **/
public class ThreadLocalUtil {

    /**
     * 记录日志操作，集中打印
     */
    private static TransmittableThreadLocal<StringBuffer> tlsb = new TransmittableThreadLocal<>();

    /**
     * 获取
     *
     * @return {@link StringBuffer}
     */
    public static StringBuffer getTlsb() {
        if (tlsb !=null){
            return tlsb.get();
        }else {
            return new StringBuffer();
        }

    }

    /**
     * 赋值
     *
     * @param sb 某人
     */
    public static void setTlsb(StringBuffer sb) {
        if (tlsb!=null){
            tlsb.set(sb);
        }

    }

    /**
     * 移除 threadlocal
     */
    public static void removeTlsb() {
        if (tlsb!=null){
            tlsb.remove();
        }
    }

    /**
     * 拼接日志操作
     *
     * @param operate 操作
     */
    public static void append(String operate){
        if (tlsb !=null){
            StringBuffer sb = tlsb.get();
            if (sb != null) {
                sb.append(StrUtil.format("《{}》《{}》{}\n",DateUtil.now(),Thread.currentThread().getName(),operate));
            }
        }
    }

    /**
     * 拼接日志操作
     *
     * @param operate 操作
     * @param object  对象
     */
    public static void append(String operate,Object object){
        if (tlsb !=null){
             StringBuffer sb = tlsb.get();
             if (object== null){
                 object = "";
             }
            if (sb != null) {
                sb.append(StrUtil.format("《{}》《{}》{}：{}\n",DateUtil.now(),Thread.currentThread().getName(),operate, object));
            }
        }
    }
}
