package cn.axzo.msg.center.notices.common.lang;

import cn.axzo.msg.center.notices.common.constans.CommonConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * 日志模板
 *
 * @author zhaoyong
 * @see LoggerTemplate
 * @since 2021-08-06 18:40
 */
@Component("loggerTemplate")
public class LoggerTemplate {

  public <T> T execute(LoggerCallback<T> action, String traceId){
    if(StringUtils.isBlank(traceId)) {
      String uuid = UUID.randomUUID().toString();
      MDC.put(CommonConstants.CTX_LOG_ID_MDC, uuid);
    } else {
      MDC.put(CommonConstants.CTX_LOG_ID_MDC, traceId);
    }
    try {
      return action.doInExecute();
    } finally {
      MDC.clear();
    }
  }

}
