java实现日志操作记录


import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;

@Aspect
@Component
@Slf4j
@Order(1)
public class ThirdApiRequestLogAspect {
    ObjectMapper objectMapper = new ObjectMapper();

    @Resource
    private CrmOperationLogMapper operationLogMapper;

    public ThirdApiRequestLogAspect() {
        log.info("初始化接口日志切面类...");
    }

    @Pointcut("execution(public * com.arvato.service.goods.api.controller.*.*(..))")
    public void controllerInteceptor() {
    }

    @Around("controllerInteceptor()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Date start = new Date();
        try {
            //数据库对应的实体
            CrmOperationLog sysLog = new CrmOperationLog();
            SysLog syslog1 = method.getAnnotation(SysLog.class);
            if (syslog1 != null) {
                //注解上的描述
                sysLog.setModule(syslog1.MODULE());
                sysLog.setMethod(syslog1.REMARK());
            }
            //请求的方法名
            String clazzName = joinPoint.getTarget().getClass().getName();
            Class<?> clazz = Class.forName(clazzName);
            String clazzSimpleName = clazz.getSimpleName();
            String methodName = signature.getName();
            sysLog.setOperationDesc(clazzSimpleName + "." + methodName);

            //请求的参数
            String[] parameterNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
            StringBuilder sb = null;
            if (Objects.nonNull(parameterNames)) {
                sb = new StringBuilder();
                for (int i = 0; i < parameterNames.length; i++) {
                    Object param = joinPoint.getArgs()[i] != null ? joinPoint.getArgs()[i] : "";
                    if (StringUtils.isNotEmpty(param.toString()) && !"request".equals(parameterNames[i]) && !"response".equals(parameterNames[i])
                            && !"modelMap".equals(parameterNames[i])) {
                        if (param instanceof Integer) {
                            sb.append(parameterNames[i] + ":" + param + "; ");
                        } else if (param instanceof String) {
                            sb.append(parameterNames[i] + ":" + param + "; ");
                        } else if (param instanceof Double) {
                            sb.append(parameterNames[i] + ":" + param + "; ");
                        } else if (param instanceof Float) {
                            sb.append(parameterNames[i] + ":" + param + "; ");
                        } else if (param instanceof Long) {
                            sb.append(parameterNames[i] + ":" + param + "; ");
                        } else if (param instanceof Boolean) {
                            sb.append(parameterNames[i] + ":" + param + "; ");
                        } else if (param instanceof Date) {
                            sb.append(parameterNames[i] + ":" + param + "; ");
                        } else if (param instanceof Timestamp) {
                            sb.append(parameterNames[i] + ":" + param + "; ");
                        } else {
                            sb.append(parameterNames[i] + ":" + getString(param) + "; ");
                        }
                    }
                }
            }
            sb = sb == null ? new StringBuilder() : sb;
            sysLog.setParams(sb.toString());
            //设置IP地址
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            sysLog.setIp(IpAddressUtil.getIpAddr(request));

           sysLog.setUserName(this.getDecodeUserName(request));
            sysLog.setCreateTime(new Date());
            log.debug("interface request startTime " + start.getTime());
            Object o = joinPoint.proceed();
            String response = objectMapper.writeValueAsString(o);

            sysLog.setTimeMin(System.currentTimeMillis() - start.getTime());
            log.debug(getString(sysLog));
            //保存系统日志
             operationLogMapper.insert(sysLog);
            return o;
        } catch (Exception ex) {
            log.error("保存系统日志失败"+ex.getMessage());
        }
       return null;
    }
    public static String getDecodeUserName(HttpServletRequest request) {
        String userName = request.getHeader("currentUserName");
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(userName)) {
            try {
                userName = URLDecoder.decode(userName, "utf-8");
            } catch (UnsupportedEncodingException var3) {
                log.error(var3.getMessage(), var3);
            }
        }

        return userName;
    }
    public static String getString(Object o) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuffer sb = new StringBuffer();
        sb.append("entity[");
        Field[] farr = o.getClass().getDeclaredFields();
        for (Field field : farr) {
            try {
                field.setAccessible(true);
                if (!ValidatorUtils.empty(field.get(o))) {
                    sb.append(field.getName());
                    sb.append("=");
                    if (field.get(o) instanceof Date) {
                        // 日期的处理
                        sb.append(sdf.format(field.get(o)));
                    } else {
                        sb.append(field.get(o));
                    }
                    sb.append("|");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        sb.append("]");
        return sb.toString();
    }
}

获取用户IP

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * IP地址工具类定义
 * @author yang.liu
 */
public class IpAddressUtil {
	public static String getIpAddr(HttpServletRequest request){
        String ipAddress = request.getHeader("x-forwarded-for");  
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
            ipAddress = request.getHeader("Proxy-Client-IP");  
        }  
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
            ipAddress = request.getHeader("WL-Proxy-Client-IP");  
        }  
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
            ipAddress = request.getRemoteAddr();  
            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){  
                //根据网卡取本机配置的IP  
                InetAddress inet=null;  
                try {  
                    inet = InetAddress.getLocalHost();  
                } catch (UnknownHostException e) {  
                    e.printStackTrace();  
                }  
                ipAddress= inet.getHostAddress();  
            }  
        }  
        //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割  
        if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15  
            if(ipAddress.indexOf(",")>0){  
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));  
            }  
        }  
        return ipAddress;   
    }
}

系统日志注解

import java.lang.annotation.*;

/**
 * 系统日志注解
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017年3月8日 上午10:19:56
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {

    String MODULE() default "操作模块";
    String REMARK() default "操作日志";
}

方法上使用自定义一注解去标识

@SysLog(MODULE = "自定义页面配置", REMARK = "删除自定义页面配置")
上一篇:java通过IP解析地理位置


下一篇:css 之 position定位