package ink.wgink.util.log;

import com.alibaba.fastjson.JSONObject;
import ink.wgink.pojo.bos.log.ApiLogBO;
import ink.wgink.pojo.bos.log.RouteLogBO;
import ink.wgink.util.date.DateUtil;
import ink.wgink.util.request.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: LogUtil
 * @Description: 日志工具
 * @Author: wanggeng
 * @Date: 2021/10/23 11:13 上午
 * @Version: 1.0
 */
public class LogUtil {
    private static final Logger LOG = LoggerFactory.getLogger(LogUtil.class);

    /**
     * 路由日志
     *
     * @param request
     * @param uri
     * @param userId
     * @param userName
     */
    public static void routeLog(HttpServletRequest request, String uri, String userId, String userName) {
        RouteLogBO routeLogBO = new RouteLogBO();
        routeLogBO.setHost(request.getRemoteAddr());
        routeLogBO.setPort(request.getLocalPort());
        routeLogBO.setRequestIp(RequestUtil.getRequestIp(request));
        routeLogBO.setContext(request.getContextPath());
        routeLogBO.setUri(uri);
        routeLogBO.setRequestTime(DateUtil.getTime());
        routeLogBO.setUserId(userId);
        routeLogBO.setUserName(userName);
        LOG.info("ROUTE-LOG:{}", JSONObject.toJSONString(routeLogBO));
    }

    /**
     * 接口日志
     *
     * @param request   请求
     * @param uri       路径
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param userId
     * @param userName
     */
    public static void apiLog(HttpServletRequest request, String uri, long startTime, long endTime, String userId, String userName) {
        long usedTime = endTime - startTime;
        ApiLogBO apiLogBO = new ApiLogBO();
        apiLogBO.setHost(request.getRemoteAddr());
        apiLogBO.setPort(request.getLocalPort());
        apiLogBO.setRequestIp(RequestUtil.getRequestIp(request));
        apiLogBO.setContext(request.getContextPath());
        apiLogBO.setUri(uri);
        apiLogBO.setRequestTime(DateUtil.getTime());
        apiLogBO.setMethod(request.getMethod());
        apiLogBO.setStartTime(startTime);
        apiLogBO.setEndTime(endTime);
        apiLogBO.setUsedTime(usedTime);
        apiLogBO.setUserId(userId);
        apiLogBO.setUserName(userName);
        LOG.info("API-LOG:{}", JSONObject.toJSONString(apiLogBO));
    }

}
