操作日志具体实现内容
下面看看它的实现步骤:
/**
* 操作日志
*/
@Target({ElementType.METHOD,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EmployeeLog {
/**模块*/
String module() default "";
/**描述*/
String description() default "";
}
/**
* 日志切面处理类
*/
@Aspect
@Component
public class EmployeeLogAspect {
@Autowired
private EmployeeLogServiceImpl employeeLogServiceImpl;
/**
* 日志切入点
*/
@Pointcut("@annotation(com.wp.annotation.EmployeeLog)")
//@Pointcut("execution(* com.wp.service.impl.EmployeeManageServiceImpl.*(..))")
public void logPointCut(){}
@AfterReturning(pointcut = "logPointCut()")
public void doAfter(JoinPoint joinPoint){
/**
* 解析Log注解
*/
String methodName = joinPoint.getSignature().getName();
Method method = currentMethod(joinPoint,methodName);
EmployeeLog log = method.getAnnotation(EmployeeLog.class);
employeeLogServiceImpl.put(joinPoint,methodName,log.module(),log.description());
}
/**
* 获取当前执行的方法
*
* @param joinPoint 连接点
* @param methodName 方法名称
* @return 方法
*/
private Method currentMethod(JoinPoint joinPoint, String methodName) {
/**
* 获取目标类的所有方法,找到当前要执行的方法
*/
Method[] methods = joinPoint.getTarget().getClass().getMethods();
Method resultMethod = null;
for (Method method : methods) {
if (method.getName().equals(methodName)) {
resultMethod = method;
break;
}
}
return resultMethod;
}
}
import com.alibaba.fastjson.JSONObject;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
import org.aspectj.lang.JoinPoint;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
private static final String LOG_CONTENT = "[类名]:%s,[方法]:%s,[参数]:%s,[IP]:%s";
public void put(JoinPoint joinPoint, String methodName, String module, String description) {
try {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
SupplierUserEditLog editLog = new SupplierUserEditLog();
//客户端地址
//String clientIp = getClientIp (request);
String ip = IPUtils.getIpAddr(request);
//获取当前用户
SysUserResponse user = UserUtil.getUser();
/* Session session = Jurisdiction.getSession();
SupplierUser u =(SupplierUser) session.getAttribute(Const.SESSION_USER);*/
editLog.setEditUser(request.getRemoteUser());
editLog.setName(user.getName());
editLog.setSupplierId(user.getSupplierId().toString());
editLog.setModule(module);
editLog.setEditTime(new Date());
editLog.setIp(ip);
editLog.setEditDetails(operateContent(joinPoint,methodName,ip,request));
editLog.setDescription(description);
//保存到数据库
userEditLogMapper.insertSelective(editLog);
} catch (Exception e) {
e.printStackTrace();
}
}
public String operateContent(JoinPoint joinPoint, String methodName, String ip, HttpServletRequest request)
throws ClassNotFoundException,NotFoundException{
String className = joinPoint.getTarget().getClass().getName();
Object[] params = joinPoint.getArgs();
String classType = joinPoint.getTarget().getClass().getName();
Class<?> clazz = Class.forName(classType);
String clazzName = clazz.getName();
Map<String,Object> nameAndArgs = getFieldsName(this.getClass(),clazzName,methodName,params);
StringBuffer buffer = new StringBuffer();
if(!CollectionUtils.isEmpty(nameAndArgs)){
Iterator it = nameAndArgs.entrySet().iterator();
while (it.hasNext()){
Map.Entry entry = (Map.Entry) it.next();
String key = (String) entry.getKey();
String value = JSONObject.toJSONString(entry.getValue());
buffer.append(key).append("=");
buffer.append(value).append("&");
}
}
if(StringUtils.isEmpty(buffer.toString())){
buffer.append(request.getQueryString());
}
return String.format(LOG_CONTENT,className,methodName,buffer.toString(),ip);
}
private Map<String,Object> getFieldsName(Class cls, String clazzName, String methodName, Object[] args)
throws NotFoundException {
Map<String,Object> map = new HashMap<>();
ClassPool pool = ClassPool.getDefault();
ClassClassPath classPath = new ClassClassPath(cls);
pool.insertClassPath(classPath);
CtClass cc = pool.get(clazzName);
CtMethod ctMethod = cc.getDeclaredMethod(methodName);
MethodInfo methodInfo = ctMethod.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attribute = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
if(attribute == null){
return map;
}
int pos = Modifier.isStatic(ctMethod.getModifiers()) ? 0 : 1;
for (int i = 0; i < ctMethod.getParameterTypes().length; i++){
map.put(attribute.variableName(i + pos),args[i]);
}
return map;
}
/**
* IP地址
*
* @author Mark sunlightcs@gmail.com
*/
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;
}
}
原网址: 访问
创建于: 2020-12-10 11:43:40
目录: default
标签: 无
未标明原创文章均为采集,版权归作者所有,转载无需和我联系,请注明原出处,南摩阿彌陀佛,知识,不只知道,要得到
最新评论