package com.lutao.cloud.admin.logback;


import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.lutao.cloud.common.security.service.CloudUser;
import com.lutao.cloud.common.security.util.SecurityUtils;
import org.slf4j.MDC;

import javax.servlet.*;
import java.io.IOException;

/**
 * MDC过滤器
 * Create by guoyc on 2021/12/21
 */
public class LogMDCFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig){
        // do noting init method
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException{
        String requestIdKey = "requestId";
        Snowflake snowflake = IdUtil.getSnowflake();
        String requestId = snowflake.nextIdStr();
        MDC.put(requestIdKey, requestId);
        // 获取uid
        CloudUser user = SecurityUtils.getUser();
        String uid = null != user ? user.getId().toString() : "";
        MDC.put("uid", uid);
        try{
            filterChain.doFilter(servletRequest, servletResponse);
        } finally{
            MDC.remove(requestIdKey);
        }
    }

    @Override
    public void destroy(){
        // do noting destroy method
    }
}