Aspect切面-系统日志

/**

* 系统日志注解

*

*/

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface SysLog {

String value() default "";

}


import org.springframework.web.context.request.RequestContextHolder;

import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class HttpContextUtils {

public static HttpServletRequest getHttpServletRequest() {

return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

}

public static String getDomain(){

HttpServletRequest request = getHttpServletRequest();

StringBuffer url = request.getRequestURL();

return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();

}

public static String getOrigin(){

HttpServletRequest request = getHttpServletRequest();

return request.getHeader("Origin");

}

}


import com.alibaba.druid.util.StringUtils;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**

* IP地址

*/

public class IPUtils {

private static Logger logger = LoggerFactory.getLogger(IPUtils.class);

/**

* 获取IP地址

*

* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址

* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址

*/

public static String getIpAddr(HttpServletRequest request) {

    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) {

        logger.error("IPUtils ERROR ", e);

        }


//        //使用代理,则获取第一个IP地址

//        if(StringUtils.isEmpty(ip) && ip.length() > 15) {

// if(ip.indexOf(",") > 0) {

// ip = ip.substring(0, ip.indexOf(","));

// }

// }

        return ip;

    }

}


/**

* 系统日志

*

*/

@Data

@TableName("sys_log")

public class SysLogEntity implements Serializable {

private static final long serialVersionUID = 1L;

@TableId

private Long id;

//用户名

private String username;

//用户操作

private String operation;

//请求方法

private String method;

//请求参数

private String params;

//执行时长(毫秒)

private Long time;

//IP地址

private String ip;

//创建时间

private Date createDate;

}


/**

*系统用户

*/

@Data

@TableName("sys_user")

public class SysUserEntity implements Serializable {

private static final long serialVersionUID = 1L;

/**

* 用户ID

*/

@TableId

private Long userId;

/**

* 用户名

*/

@NotBlank(message="用户名不能为空", groups = {AddGroup.class, UpdateGroup.class})

private String username;

/**

* 密码

*/

@NotBlank(message="密码不能为空", groups = AddGroup.class)

private String password;

/**

* 盐

*/

private String salt;

/**

* 邮箱

*/

@NotBlank(message="邮箱不能为空", groups = {AddGroup.class, UpdateGroup.class})

@Email(message="邮箱格式不正确", groups = {AddGroup.class, UpdateGroup.class})

private String email;

/**

* 手机号

*/

private String mobile;

/**

* 状态  0:禁用  1:正常

*/

private Integer status;

/**

* 角色ID列表

*/

@TableField(exist=false)

private List roleIdList;

/**

* 创建者ID

*/

private Long createUserId;

/**

* 创建时间

*/

private Date createTime;

}


@Aspect

@Component

public class SysLogAspect {

@Autowired

private SysLogService sysLogService;

@Pointcut("@annotation(com.公司.部门.annotation.SysLog)")

public void logPointCut() {

}

@Around("logPointCut()")

public Object around(ProceedingJoinPoint point) throws Throwable {

long beginTime = System.currentTimeMillis();

//执行方法

Object result = point.proceed();

//执行时长(毫秒)

long time = System.currentTimeMillis() - beginTime;

//保存日志(切面,时间)

saveSysLog(point, time);

return result;

}

private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {

//方法签名

MethodSignature signature = (MethodSignature) joinPoint.getSignature();

Method method = signature.getMethod();

//

SysLogEntity sysLog = new SysLogEntity();

SysLog syslog = method.getAnnotation(SysLog.class);

if(syslog != null){

//注解上的描述

sysLog.setOperation(syslog.value());

}

//请求的方法名

String className = joinPoint.getTarget().getClass().getName();

String methodName = signature.getName();

sysLog.setMethod(className + "." + methodName + "()");

//请求的参数

Object[] args = joinPoint.getArgs();

try{

String params = new Gson().toJson(args);

sysLog.setParams(params);

}catch (Exception e){

}

//获取request

HttpServletRequest request = HttpContextUtils.getHttpServletRequest();

//设置IP地址

sysLog.setIp(IPUtils.getIpAddr(request));

//用户名

String username = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUsername();

sysLog.setUsername(username);

sysLog.setTime(time);

sysLog.setCreateDate(new Date());

//保存系统日志

sysLogService.save(sysLog);

}

}

你可能感兴趣的:(Aspect切面-系统日志)