SpringBoot日志记录到数据库操作部分

添加日志类操作

DROP TABLE IF EXISTS `sys_log`;
CREATE TABLE `sys_log` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `telephone` varchar(50) DEFAULT NULL,
  `operation` varchar(100) DEFAULT NULL,
  `method` varchar(200) DEFAULT NULL,
  `params` varchar(5000) DEFAULT NULL,
  `ip` varchar(64) DEFAULT NULL,
  `createdTime` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `time` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

POJO类操作

@Data
public class SysLog { private Long id; private String username; private String telephone; private String operation; private String method; private String params; private Long time; private String ip; private Date createdTime;

......省略部分代码
}

省略 CRUD ,mapper,service,impl代码,

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.example.tsfunproj.entity.SysLog;
import com.example.tsfunproj.entity.User;
import com.example.tsfunproj.service.SysLogService;
import com.example.tsfunproj.utils.IpUtils;
import com.example.tsfunproj.utils.JwtUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;


@Aspect
@Component
public class SysLogAspect {

    @Autowired
    private SysLogService sysLogService;

    @Around("execution(* com.example.tsfunproj.controller.v1.*.*(..))")
    public Object advice(ProceedingJoinPoint pjp) throws Throwable{
        long st=System.currentTimeMillis();
        Object result=pjp.proceed();
        long et=System.currentTimeMillis();
        long time=et-st;
        try {
            saveSysLog(time, pjp);
        }catch(Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public void saveSysLog(Long time,ProceedingJoinPoint pjp) throws JsonProcessingException{
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpSession session=request.getSession();
        String username="visitor";// 通用的用户名
        if(session.getAttribute("user")!=null) {
            User user=(User)session.getAttribute("user");
            username = user.getUsername();
        }
        String operation="TODO"; // 后续实现
        String className=pjp.getTarget().getClass().getName(); // 包名.类名
        String method=className+"."+pjp.getSignature().getName();
        // params 从pjp中获取
        Object[] paramsObj=pjp.getArgs();
        // 将Ojbect类型的参数中的数据生成对应的字符串表示
        String params=new ObjectMapper().writeValueAsString(paramsObj);
        String ip= IpUtils.getIpAddr();
        Date createdTime=new Date();
        String token = request.getHeader("userToken");
        String telephone = "12345000000";
        if(token!=null&&!token.equals("")) {
           telephone = JwtUtils.getTelephone(token);
        }
        SysLog sysLogDO=new SysLog(null, username,telephone,operation, method, params, time, ip, createdTime);
        sysLogService.insertSelect(sysLogDO);
    }
}

获取IpUtils工具类

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class IpUtils {

    public static String getIpAddr() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ip;
    }
}

  

猜你喜欢

转载自www.cnblogs.com/EarlyBridVic/p/12566453.html