Переглянути джерело

系统日志修改

git-svn-id: https://192.168.57.71/svn/jsgkj@1164 931142cf-59ea-a443-aa0e-51397b428577
ld_zhouk 8 роки тому
батько
коміт
2e88cad48d

+ 0 - 9
gkaqv2/trunk/modules/web/src/main/java/com/xt/js/gkaq/common/GlobalData.java

@@ -5,13 +5,4 @@ package com.xt.js.gkaq.common;
  */
 public class GlobalData {
 
-    public static final String CHK_YES = "Y";
-
-    public static final String CHK_NO = "N";
-
-    public static final String LEAF_YES = "Y";
-
-    public static final String LEAF_NO = "N";
-
-    public static final String LEAF_BTN = "B";
 }

+ 181 - 26
gkaqv2/trunk/modules/web/src/main/java/com/xt/js/gkaq/common/log/aspect/SysLogAspect.java

@@ -1,12 +1,24 @@
 package com.xt.js.gkaq.common.log.aspect;
 
+import java.lang.reflect.Field;
 import java.lang.reflect.Method;
+import java.util.Date;
 
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.ibatis.javassist.ClassClassPath;
+import org.apache.ibatis.javassist.ClassPool;
+import org.apache.ibatis.javassist.CtClass;
+import org.apache.ibatis.javassist.CtMethod;
+import org.apache.ibatis.javassist.Modifier;
+import org.apache.ibatis.javassist.bytecode.CodeAttribute;
+import org.apache.ibatis.javassist.bytecode.LocalVariableAttribute;
+import org.apache.ibatis.javassist.bytecode.MethodInfo;
 import org.aspectj.lang.JoinPoint;
 import org.aspectj.lang.Signature;
+import org.aspectj.lang.annotation.After;
 import org.aspectj.lang.annotation.AfterThrowing;
 import org.aspectj.lang.annotation.Aspect;
-import org.aspectj.lang.annotation.Before;
 import org.aspectj.lang.annotation.Pointcut;
 import org.aspectj.lang.reflect.MethodSignature;
 import org.slf4j.Logger;
@@ -17,6 +29,8 @@ import org.springframework.stereotype.Component;
 import com.xt.js.gkaq.common.Constants;
 import com.xt.js.gkaq.common.ex.BusinessException;
 import com.xt.js.gkaq.common.log.annotation.SysLog;
+import com.xt.js.gkaq.common.util.DateUtil;
+import com.xt.js.gkaq.common.util.IpUtil;
 import com.xt.js.gkaq.frame.model.SysLogModel;
 import com.xt.js.gkaq.frame.service.SysLogService;
 
@@ -31,30 +45,35 @@ public class SysLogAspect {
     // 日志对象
     private static final Logger logger = LoggerFactory.getLogger(SysLogAspect.class);
 
+    private static String[] paramTypes = { "java.lang.Integer", "java.lang.Double", "java.lang.Float",
+            "java.lang.Long", "java.lang.Short", "java.lang.Byte", "java.lang.Boolean", "java.lang.Char",
+            "java.lang.String", "int", "double", "long", "short", "byte", "boolean", "char", "float" };
+
     // 日志切入点
     @Pointcut("@annotation(com.xt.js.gkaq.common.log.annotation.SysLog)")
     public void sysLogPointcut() {
     }
 
+    // /**
+    // * 前置通知
+    // *
+    // * @param joinPoint
+    // */
+    // @Before("sysLogPointcut()")
+    // public void doBefore(JoinPoint joinPoint) {
+    // genSysLog(joinPoint, null);
+    // }
+
     /**
-     * 前置通知
+     * 置通知
      * 
      * @param joinPoint
      */
-    @Before("sysLogPointcut()")
-    public void doBefore(JoinPoint joinPoint) {
+    @After("sysLogPointcut()")
+    public void doAfter(JoinPoint joinPoint) {
         genSysLog(joinPoint, null);
     }
 
-    // /**
-    // * 后置通知
-    // * @param joinPoint
-    // */
-    // @AfterReturning(pointcut = "sysLogPointcut()")
-    // public void doAfter(JoinPoint joinPoint) {
-    // genSysLog(joinPoint, null);
-    // }
-
     /**
      * 异常通知
      * 
@@ -79,37 +98,47 @@ public class SysLogAspect {
             // 获取目标类名
             String targetName = joinPoint.getTarget().getClass().getName();
             // 类路径
-            String classPath = targetName + "." + methodName + "()";
+            String logPath = targetName + "." + methodName + "()";
             // 获取系统日志注解
             SysLog sysLog = getSysLogAnnotation(joinPoint);
             if (sysLog == null) {
-                logger.error("{}获取系统日志注解为空!", classPath);
+                logger.error("{}获取系统日志注解为空!", logPath);
                 return;
             }
 
-            String description = sysLog.description();
-            String type = sysLog.type();
+            String[] paramNames = getMethodParamNames(this.getClass(), targetName, methodName);
+            String logParam = "";
+            if (paramNames != null) {
+                logParam = genMethodParamInfo(paramNames, joinPoint);
+            }
+
+            String logMsg = sysLog.description();
+            String logType = sysLog.type();
             if (ex != null) {
                 if (ex instanceof BusinessException) {
-                    type = Constants.LOG_TYPE_2;
+                    logType = Constants.LOG_TYPE_2;
                     BusinessException bex = (BusinessException) ex;
-                    description += "[发生业务异常,异常代码:" + bex.getErrorCode() + ",异常信息:" + bex.getErrorMsg() + "]";
+                    logMsg += "[发生业务异常,异常代码:" + bex.getErrorCode() + ",异常信息:" + bex.getErrorMsg() + "]";
                 } else {
-                    type = Constants.LOG_TYPE_1;
-                    description += "[发生异常:" + ex.getMessage() + "]";
+                    logType = Constants.LOG_TYPE_1;
+                    logMsg += "[发生异常:" + ex.getMessage() + "]";
                 }
             }
-            logger.info("生成系统日志[日志类路径:{},日志类型:{},日志描述:{}]", classPath, type, description);
+            HttpServletRequest request = null;
+            String ip = "";//IpUtil.getIpAddr(request);
+            logger.info("生成系统日志[日志类型:{},日志路径:{},日志参数:{},日志描述:{},客户端IP:{}]", logType, logPath, logParam, logMsg);
 
             // 数据库日志
             SysLogModel log = new SysLogModel();
-            log.setClassPath(classPath);
-            log.setType(type);
-            log.setMessage(description);
+            log.setLogType(logType);
+            log.setLogPath(logPath);
+            log.setLogParam(logParam);
+            log.setLogMsg(logMsg);
+            log.setClientIp(ip);
             // 保存数据库
             sysLogService.save(log);
         } catch (Exception exp) {
-            logger.error("生成系统日志发生异常:", exp);
+            logger.error("生成系统日志发生异常", exp);
         }
     }
 
@@ -133,4 +162,130 @@ public class SysLogAspect {
         return null;
     }
 
+    /**
+     * 获取方法参数的名称
+     * 
+     * @param thisClass
+     * @param clazzName
+     * @param methodName
+     * @return
+     */
+    private static String[] getMethodParamNames(Class<?> thisClass, String clazzName, String methodName) {
+
+        String[] paramNames = null;
+        try {
+            ClassPool pool = ClassPool.getDefault();
+
+            ClassClassPath classPath = new ClassClassPath(thisClass);
+            pool.insertClassPath(classPath);
+
+            CtClass cc = pool.get(clazzName);
+            CtMethod cm = cc.getDeclaredMethod(methodName);
+            MethodInfo methodInfo = cm.getMethodInfo();
+            CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
+            LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute
+                    .getAttribute(LocalVariableAttribute.tag);
+            if (attr == null) {
+                throw new Exception(cc.getName() + " : LocalVariableAttribute is null!");
+            }
+            paramNames = new String[cm.getParameterTypes().length];
+            int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
+            for (int i = 0; i < paramNames.length; i++) {
+                // paramNames即参数名
+                paramNames[i] = attr.variableName(i + pos);
+            }
+        } catch (Exception ex) {
+            logger.error("系统日志生成,获取方法参数的名称时发生异常:", ex);
+        }
+        return paramNames;
+    }
+
+    /**
+     * 生成方法参数信息
+     * 
+     * @param paramNames
+     * @param joinPoint
+     * @return
+     */
+    private static String genMethodParamInfo(String[] paramNames, JoinPoint joinPoint) {
+
+        Object[] args = joinPoint.getArgs();
+        StringBuilder paramInfo = new StringBuilder();
+        boolean clazzFlag = true;
+        try {
+            for (int i = 0; i < args.length; i++) {
+                clazzFlag = true;
+                Object arg = args[i];
+                if (arg == null) {
+                    continue;
+                }
+                paramInfo.append(paramNames[i]).append(" ");
+                // 获取对象类型
+                String typeName = arg.getClass().getName();
+
+                for (String paramType : paramTypes) {
+                    if (paramType.equals(typeName)) {
+                        paramInfo.append("= ").append(arg).append("; ");
+                        clazzFlag = false;
+                        break;
+                    }
+                }
+                if (clazzFlag) {
+                    paramInfo.append(getClazzParamInfo(arg));
+                }
+            }
+        } catch (Exception ex) {
+            logger.error("系统日志生成,生成方法参数信息时发生异常:", ex);
+        }
+        return paramInfo.toString();
+    }
+
+    /**
+     * 获取非基本类型参数信息
+     * 
+     * @param obj
+     * @throws IllegalAccessException
+     * @throws IllegalArgumentException
+     */
+    public static String getClazzParamInfo(Object obj) throws IllegalArgumentException, IllegalAccessException {
+
+        if (obj == null) {
+            return "";
+        }
+
+        Field[] fields = obj.getClass().getDeclaredFields();
+        StringBuilder paramInfo = new StringBuilder();
+        boolean clazzFlag = true;
+        String dateType = "java.util.Date";
+
+        paramInfo.append("[");
+        for (Field field : fields) {
+            field.setAccessible(true);
+            if (field.get(obj) == null) {
+                continue;
+            }
+            clazzFlag = true;
+            for (String paramType : paramTypes) {
+                if (paramType.equals(field.getType().getName())) {
+                    paramInfo.append(field.getName()).append(" = ").append(field.get(obj)).append("; ");
+                    clazzFlag = false;
+                    break;
+                }
+            }
+            if (clazzFlag) {
+                // 日期类型处理
+                if (dateType.equals(field.getType().getName())) {
+                    Date date = (Date) field.get(obj);
+                    String dateStr = DateUtil.DateToStr(date, DateUtil.FORMAT_DATE);
+                    paramInfo.append(field.getName()).append(" = ").append(dateStr).append("; ");
+                } else {
+                    // 递归
+                    getClazzParamInfo(field.get(obj));
+                }
+            }
+        }
+        paramInfo.append("]");
+
+        return paramInfo.toString();
+    }
 }

+ 1 - 1
gkaqv2/trunk/modules/web/src/main/java/com/xt/js/gkaq/common/CustomDateSerializer.java → gkaqv2/trunk/modules/web/src/main/java/com/xt/js/gkaq/common/util/CustomDateSerializer.java

@@ -1,4 +1,4 @@
-package com.xt.js.gkaq.common;
+package com.xt.js.gkaq.common.util;
 
 import java.io.IOException;
 import java.text.SimpleDateFormat;

+ 64 - 0
gkaqv2/trunk/modules/web/src/main/java/com/xt/js/gkaq/common/util/DateUtil.java

@@ -0,0 +1,64 @@
+package com.xt.js.gkaq.common.util;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+
+/**
+ * 日期工具类
+ */
+public class DateUtil {
+
+    public static String FORMAT_DATE = "yyyy-MM-dd";
+    public static String FORMAT_TIME = "yyyy-MM-dd HH:mm:ss";
+    public static String FORMAT_TIMESTAMP = "yyMMddHHmmssSSS";
+    public static String FORMAT_MONTH = "yyyyMM";
+
+    public static String FORMAT_TRAN_DATE = "yyyyMMdd";
+    public static String FORMAT_TRAN_TIME = "HHmmss";
+    public static String FORMAT_TRAN_TIMESTAMP = "yyyyMMddHHmmssSSS";
+
+    /**
+     * 日期转换字符串
+     * 
+     * @param date
+     * @return str
+     */
+    public static String DateToStr(Date date, String pattern) {
+
+        SimpleDateFormat format = new SimpleDateFormat(pattern);
+        String str = format.format(date);
+        return str;
+    }
+
+    /**
+     * 字符串转换日期
+     * 
+     * @param str
+     * @return date
+     */
+    public static Date StrToDate(String str, String pattern) {
+
+        SimpleDateFormat format = new SimpleDateFormat(pattern);
+        Date date = null;
+        try {
+            date = format.parse(str);
+        } catch (ParseException e) {
+            e.printStackTrace();
+        }
+        return date;
+    }
+
+    /**
+     * 月份差�
+     * @param now
+     * @param next
+     * @return
+     */
+    public static int getMonthDiff(Calendar now, Calendar next) {
+        return (now.get(Calendar.YEAR) - next.get(Calendar.YEAR)) * 12
+                + now.get(Calendar.MONTH) - next.get(Calendar.MONTH);
+    }
+
+}

+ 64 - 0
gkaqv2/trunk/modules/web/src/main/java/com/xt/js/gkaq/common/util/IpUtil.java

@@ -0,0 +1,64 @@
+package com.xt.js.gkaq.common.util;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+
+import javax.servlet.http.HttpServletRequest;
+
+/**
+ * IP工具类
+ */
+public class IpUtil {
+
+    /**
+     * 获取客户端IP地址
+     * 
+     * @param request
+     * @return
+     */
+    public static String getIpAddr(HttpServletRequest request) {
+        String ip = request.getHeader("x-forwarded-for");
+        if (unknownIp(ip)) {
+            ip = request.getHeader("Proxy-Client-IP");
+        }
+        if (unknownIp(ip)) {
+            ip = request.getHeader("WL-Proxy-Client-IP");
+        }
+        if (unknownIp(ip)) {
+            ip = request.getHeader("HTTP_CLIENT_IP");
+        }
+        if (unknownIp(ip)) {
+            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
+        }
+        if (unknownIp(ip)) {
+            ip = request.getRemoteAddr();
+            if (ip.equals("127.0.0.1")) {
+                // 根据网卡取本机配置的IP
+                InetAddress inet = null;
+                try {
+                    inet = InetAddress.getLocalHost();
+                } catch (UnknownHostException e) {
+                    e.printStackTrace();
+                }
+                ip = inet.getHostAddress();
+            }
+        }
+        // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
+        if (ip != null && ip.length() > 15) {
+            if (ip.indexOf(",") > 0) {
+                ip = ip.substring(0, ip.indexOf(","));
+            }
+        }
+        return ip;
+    }
+
+    /**
+     * 是否未知IP
+     * 
+     * @param ip
+     * @return
+     */
+    private static boolean unknownIp(String ip) {
+        return ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip);
+    }
+}

+ 29 - 0
gkaqv2/trunk/modules/web/src/main/java/com/xt/js/gkaq/common/util/UserSessionListener.java

@@ -0,0 +1,29 @@
+package com.xt.js.gkaq.common.util;
+
+import java.util.Date;
+
+import javax.servlet.http.HttpSessionBindingEvent;
+import javax.servlet.http.HttpSessionBindingListener;
+
+/**
+ * 用户会话监听
+ */
+public class UserSessionListener implements HttpSessionBindingListener {
+    int uid;
+
+    public int getUid() {
+        return uid;
+    }
+
+    public void setUid(int uid) {
+        this.uid = uid;
+    }
+
+    public void valueBound(HttpSessionBindingEvent arg0) {
+        System.out.println(uid + "登录了" + new Date());
+    }
+
+    public void valueUnbound(HttpSessionBindingEvent arg0) {
+        System.out.println(uid + "下线了" + new Date());
+    }
+}

+ 2 - 2
gkaqv2/trunk/modules/web/src/main/java/com/xt/js/gkaq/web/ctl/LoginCtl.java

@@ -10,8 +10,8 @@ import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestMapping;
 
 import com.xt.js.gkaq.common.BaseCtl;
+import com.xt.js.gkaq.common.Constants;
 import com.xt.js.gkaq.frame.model.MenuModel;
-import com.xt.js.gkaq.frame.system.FrameParam;
 
 @Controller
 public class LoginCtl extends BaseCtl {
@@ -27,7 +27,7 @@ public class LoginCtl extends BaseCtl {
         Session session = SecurityUtils.getSubject().getSession();
         // TODO »ñÈ¡µ±Ç°Óû§²Ëµ¥DEMO
         @SuppressWarnings("unchecked")
-        List<MenuModel> menuList = (List<MenuModel>) session.getAttribute(FrameParam.SESSION_KEY_MENUS);
+        List<MenuModel> menuList = (List<MenuModel>) session.getAttribute(Constants.SESSION_KEY_MENUS);
         for (MenuModel menu : menuList) {
             System.out.println("menu : " + menu.getCode() + " | " + menu.getName());
         }

+ 3 - 3
gkaqv2/trunk/modules/web/src/main/java/com/xt/js/gkaq/web/ctl/MenuCtl.java

@@ -15,7 +15,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
 
 import com.alibaba.fastjson.JSONArray;
 import com.xt.js.gkaq.common.BaseCtl;
-import com.xt.js.gkaq.common.GlobalData;
+import com.xt.js.gkaq.common.Constants;
 import com.xt.js.gkaq.frame.model.MenuModel;
 import com.xt.js.gkaq.frame.service.ButtonService;
 import com.xt.js.gkaq.frame.service.MenuService;
@@ -94,9 +94,9 @@ public class MenuCtl extends BaseCtl {
         }
         List<MenuModel> list = null;
 
-        if (GlobalData.LEAF_BTN.equals(model.getLeaf())) {
+        if (Constants.LEAF_BTN.equals(model.getLeaf())) {
             list = new ArrayList<MenuModel>();
-        } else if (GlobalData.LEAF_YES.equals(model.getLeaf())) {
+        } else if (Constants.LEAF_YES.equals(model.getLeaf())) {
             list = menuService.findAllBtnByCond(model);
         } else {
             list = menuService.findAllByCond(model);

+ 16 - 15
gkaqv2/trunk/modules/web/src/main/java/com/xt/js/gkaq/web/ctl/UserCtl.java

@@ -14,7 +14,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.ResponseBody;
 
 import com.xt.js.gkaq.common.BaseCtl;
-import com.xt.js.gkaq.common.GlobalData;
+import com.xt.js.gkaq.common.Constants;
 import com.xt.js.gkaq.common.ex.BusinessException;
 import com.xt.js.gkaq.common.log.annotation.SysLog;
 import com.xt.js.gkaq.frame.model.UserGroupModel;
@@ -47,14 +47,14 @@ public class UserCtl extends BaseCtl {
     }
 
 	/**
-	 * 锟斤拷始锟斤拷页锟斤拷锟斤拷锟斤拷锟斤拷
+	 * 初始化页面加载数据
 	 * @throws UnsupportedEncodingException 
 	 */
     @RequestMapping("list")
     @ResponseBody
     @SysLog(description="用户列表查询")
 	public PageInfo<UserModel> getPageInfo(UserVo vo) throws UnsupportedEncodingException {
-		// 锟斤拷始锟斤拷锟斤拷锟斤拷
+		// 初始化参数
 		if (null == vo.getPage() || vo.getPage() < 1) {
 			vo.setPage(1);
 		}
@@ -91,7 +91,7 @@ public class UserCtl extends BaseCtl {
     }
 
     /**
-     * 锟斤拷锟斤拷
+     * 保存
      * @param vo
      * @return
      */
@@ -100,25 +100,25 @@ public class UserCtl extends BaseCtl {
     @Transactional
     @SysLog(description="保存用户数据")
     public WebJsonResult save(UserVo vo) {
-        // 锟斤拷锟斤拷
+        // 新增
         if(StringUtils.isEmpty(vo.getId())) {
             UserModel model = new UserModel();
             BeanUtils.copyProperties(vo, model);
-            // 锟斤拷录锟斤拷锟斤拷:123456
+            // 登录密码:123456
             String pwd = new Sha256Hash("123456").toHex();
             model.setLoginPassword(pwd);
             userService.add(model);
             UserInfoModel userInfoModel = new UserInfoModel();
             BeanUtils.copyProperties(vo, userInfoModel);
             userInfoModel.setId(model.getId());
-            // 锟角凤拷营锟斤拷
-            if (GlobalData.CHK_YES.equals(vo.getIfAdmin())) {
-                userInfoModel.setIfOperator(GlobalData.CHK_NO);
+            // 是否经营人
+            if (Constants.CHK_YES.equals(vo.getIfAdmin())) {
+                userInfoModel.setIfOperator(Constants.CHK_NO);
             } else {
-                userInfoModel.setIfOperator(GlobalData.CHK_YES);
+                userInfoModel.setIfOperator(Constants.CHK_YES);
             }
-            // 锟斤拷锟斤拷锟斤拷锟斤拷
-            if (GlobalData.CHK_YES.equals(vo.getIfShip())) {
+            // 所属船代
+            if (Constants.CHK_YES.equals(vo.getIfShip())) {
                 userInfoModel.setBelongsOrg(userInfoModel.getBelongsShip());
             }
             userInfoService.add(userInfoModel);
@@ -127,7 +127,7 @@ public class UserCtl extends BaseCtl {
             userGroupModel.setGroupId(vo.getGroupid());
             userGroupService.add(userGroupModel);
         } else {
-            // 锟斤拷锟斤拷
+            // 更新
             UserModel model = userService.findById(vo.getId());
             BeanUtils.copyProperties(vo, model);
             userService.update(model);
@@ -144,6 +144,7 @@ public class UserCtl extends BaseCtl {
 
     @RequestMapping("getRecord")
     @ResponseBody
+    @SysLog(description="用户列表查询")
     public UserVo getRecord(String id) {
 
         UserModel model = userInfoService.findById(id);
@@ -167,8 +168,8 @@ public class UserCtl extends BaseCtl {
 			for(String id : idArr) {
 				if(StringUtils.isNotEmpty(id)) {
 					cnt += userService.deleteLogicByID(id);
-					/*userInfoService.deleteLogicByID(id);
-					userGroupService.deleteLogicByID(id);*/
+					userInfoService.deleteLogicByID(id);
+					userGroupService.deleteLogicByID(id);
 				}
 			}
 		}

+ 1 - 1
gkaqv2/trunk/modules/web/src/main/java/com/xt/js/gkaq/web/vo/UserVo.java

@@ -6,7 +6,7 @@ import org.springframework.format.annotation.DateTimeFormat;
 
 import com.fasterxml.jackson.databind.annotation.JsonSerialize;
 import com.xt.js.gkaq.common.BaseVo;
-import com.xt.js.gkaq.common.CustomDateSerializer;
+import com.xt.js.gkaq.common.util.CustomDateSerializer;
 
 public class UserVo extends BaseVo {
     private String id;