Przeglądaj źródła

:zap: fix 日志输出的bug

Aron 5 lat temu
rodzic
commit
865c47dfa8

+ 26 - 22
src/main/java/com/ifast/api/util/JWTUtil.java

@@ -20,6 +20,7 @@ import org.apache.shiro.authc.AuthenticationException;
 import org.apache.shiro.authc.ExpiredCredentialsException;
 import org.springframework.stereotype.Component;
 
+import javax.annotation.PostConstruct;
 import java.io.UnsupportedEncodingException;
 import java.util.Calendar;
 import java.util.Date;
@@ -28,14 +29,19 @@ import java.util.Date;
  * <pre>
  * jwt工具类
  * </pre>
- * 
+ *
  * <small> 2018年4月28日 | Aron</small>
  */
 @Slf4j
 @Component
 public class JWTUtil {
 
-	public static String userPrimaryKey = SpringContextHolder.getBean(JWTConfigProperties.class).getUserPrimaryKey();
+    private static JWTConfigProperties jwtConfigProperties = null;
+
+    @PostConstruct
+    public void init() {
+        jwtConfigProperties = SpringContextHolder.getBean(JWTConfigProperties.class);
+    }
 
     public static String STR_DELIMITER = "\\.";
     public static int LEVEL = 3;
@@ -43,7 +49,7 @@ public class JWTUtil {
 
     public static TokenVO createToken(UserDO user) {
         TokenVO vo = new TokenVO();
-        String token        = JWTUtil.sign(user.getId() + "", user.getUsername() + user.getPassword(), AppUserServiceImpl.Holder.jwtConfig.getExpireTime());
+        String token = JWTUtil.sign(user.getId() + "", user.getUsername() + user.getPassword(), AppUserServiceImpl.Holder.jwtConfig.getExpireTime());
         String refreshToken = JWTUtil.sign(user.getId() + "", user.getUsername() + user.getPassword(), AppUserServiceImpl.Holder.jwtConfig.getRefreshTokenExpire(), true);
         vo.setToken(token);
         vo.setRefleshToken(refreshToken);
@@ -54,6 +60,7 @@ public class JWTUtil {
 
     /**
      * token是否过期
+     *
      * @return true:过期
      */
     public static boolean isTokenExpired(String token) {
@@ -65,35 +72,32 @@ public class JWTUtil {
     /**
      * <pre>
      * </pre>
-     * 
+     *
      * <small> 2018年4月28日 | Aron</small>
-     * 
-     * @param token
-     *            即jwt
-     * @param userId
-     *            用户id
-     * @param secret
-     *            用户的secret
+     *
+     * @param token  即jwt
+     * @param userId 用户id
+     * @param secret 用户的secret
      */
     public static void verify(String token, String userId, String secret) {
         try {
             Algorithm algorithm = Algorithm.HMAC256(secret);
-            JWTVerifier verifier = JWT.require(algorithm).withClaim(userPrimaryKey, userId).build();
+            JWTVerifier verifier = JWT.require(algorithm).withClaim(jwtConfigProperties.getUserPrimaryKey(), userId).build();
             verifier.verify(token);
         } catch (TokenExpiredException exception) {
             log.info("token 签名校验失败,过期:{}", token);
             throw new ExpiredCredentialsException(EnumErrorCode.apiAuthorizationExpired.getMsg());
-        }catch (InvalidClaimException exception2){
+        } catch (InvalidClaimException exception2) {
             log.info("token 签名校验失败,数据异常:{}", token);
             throw new AuthenticationException(EnumErrorCode.apiAuthorizationInvalid.getMsg());
-        }catch (Exception exception3){
+        } catch (Exception exception3) {
             log.info("token 签名校验失败:{}", token);
             throw new IFastApiException(EnumErrorCode.apiAuthorizationInvalid.getCodeStr());
         }
     }
 
     public static void verify(String token, String userId, String secret, boolean isRefreshToken) {
-        if(isRefreshToken){
+        if (isRefreshToken) {
             secret += "_REFRESH_TOKEN";
         }
         verify(token, userId, secret);
@@ -103,18 +107,18 @@ public class JWTUtil {
      * <pre>
      * 获得token中的信息无需secret解密也能获得
      * </pre>
-     * 
+     *
      * <small> 2018年4月28日 | Aron</small>
-     * 
+     *
      * @param token token
      */
     public static String getUserId(String token) {
         try {
             DecodedJWT jwt = JWT.decode(token);
-            Claim claim = jwt.getClaim(userPrimaryKey);
+            Claim claim = jwt.getClaim(jwtConfigProperties.getUserPrimaryKey());
             return claim.asString();
         } catch (JWTDecodeException e) {
-            log.warn("token解码获取{}失败:{}",userPrimaryKey, token);
+            log.warn("token解码获取{}失败:{}", jwtConfigProperties.getUserPrimaryKey(), token);
             return null;
         }
     }
@@ -124,7 +128,7 @@ public class JWTUtil {
      * </pre>
      *
      * <small> 2018年4月28日 | Aron</small>
-     * 
+     *
      * @param userId 用户标识
      * @param secret 加密密钥
      * @param expire 有效期,毫秒值
@@ -133,7 +137,7 @@ public class JWTUtil {
         try {
             Date date = new Date(System.currentTimeMillis() + expire);
             Algorithm algorithm = Algorithm.HMAC256(secret);
-            return JWT.create().withClaim(userPrimaryKey, userId).withExpiresAt(date).sign(algorithm);
+            return JWT.create().withClaim(jwtConfigProperties.getUserPrimaryKey(), userId).withExpiresAt(date).sign(algorithm);
         } catch (UnsupportedEncodingException e) {
             e.printStackTrace();
             throw new IFastApiException(EnumErrorCode.apiAuthorizationSignFailed.getCodeStr());
@@ -151,7 +155,7 @@ public class JWTUtil {
      * @param expire 有效期,毫秒值
      */
     public static String sign(String userId, String secret, long expire, boolean isRefreshToken) {
-        if(isRefreshToken){
+        if (isRefreshToken) {
             secret += "_REFRESH_TOKEN";
         }
         return sign(userId, secret, expire);

+ 78 - 37
src/main/java/com/ifast/common/aspect/LogAspect.java

@@ -1,9 +1,11 @@
 package com.ifast.common.aspect;
 
+import com.ifast.api.exception.IFastApiException;
 import com.ifast.common.annotation.Log;
 import com.ifast.common.config.IFastProperties;
 import com.ifast.common.dao.LogDao;
 import com.ifast.common.domain.LogDO;
+import com.ifast.common.type.EnumErrorCode;
 import com.ifast.common.utils.*;
 import com.ifast.sys.domain.UserDO;
 import lombok.AllArgsConstructor;
@@ -20,6 +22,7 @@ import javax.servlet.http.HttpServletRequest;
 import java.lang.reflect.Method;
 import java.util.Date;
 import java.util.Map;
+import java.util.Objects;
 
 /**
  * <pre>
@@ -37,32 +40,62 @@ public class LogAspect {
     private final LogDao logMapper;
     private final IFastProperties iFastProperties;
 
-    @Pointcut("execution(public * com.ifast.*.controller.*.*(..))")
-    public void logController(){}
-    
+
+    @Pointcut("execution(public * com.ifast..*.controller.*.*(..))")
+    public void logController() {}
+
     /**
      * 记录controller日志,包括请求、ip、参数、响应结果
      */
     @Around("logController()")
-    public Object controller(ProceedingJoinPoint point) {
+    public Object controller(ProceedingJoinPoint point) throws Throwable {
 
         long beginTime = System.currentTimeMillis();
-        Object result = null;
+        long time = 0L;
+        Object result;
         try {
             result = point.proceed();
-        } catch (Throwable throwable) {
-            throwable.printStackTrace();
-        }
-        long time = System.currentTimeMillis() - beginTime;
+            time = System.currentTimeMillis() - beginTime;
+        }catch (Exception e){
+
+            if(e instanceof IllegalArgumentException){
+                result = Result.build(EnumErrorCode.illegalArgument.getCode(), e.getMessage());
+            }else if(e instanceof IFastApiException){
+                log.info("已知异常:{}, 继续抛出",e.getClass());
+                result = Result.buildByErrorCode(e.getMessage());
+            }else {
+                log.info("未知异常:{}, 继续抛出",e.getClass());
+                result = Result.build(EnumErrorCode.unknowFail.getCode(), EnumErrorCode.unknowFail.getMsg());
+            }
 
-        print(point, result, time, iFastProperties.isLogPretty());
-        saveLog(point, time);
+            try {
+                print(point, result, time, iFastProperties.isLogPretty());
+                saveLog(point, time);
+            } catch (Exception e1) {
+                log.warn("日志输出|保存错误: {}", e1.getMessage());
+            }
+
+            throw e;
+
+        }
+        try {
+            print(point, result, time, iFastProperties.isLogPretty());
+            saveLog(point, time);
+        } catch (Exception e) {
+            log.warn("日志输出|保存错误: {}", e.getMessage());
+        }
 
         return result;
     }
 
     /**
      * 日志打印
+     *
+     * 注意:
+     * 1. 被外层拦截器拦截将不会记录
+     * 2. 有些特殊情况下打印的日志与实际返回不相同,可参考全局异常处理
+     * 3. 用于常规请求的日志打印,方便调试
+     *
      * @param point
      * @param result
      * @param time
@@ -70,16 +103,23 @@ public class LogAspect {
      */
     private void print(ProceedingJoinPoint point, Object result, long time, boolean isLogPretty) {
         HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
-        if(isLogPretty){
-            log.info("User request info  ---- {} ---- S", DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN_19));
-            log.info("请求接口: {} {}@{} {} {}.{}", request.getMethod(), request.getRequestURI(), ShiroUtils.getUserId(), IPUtils.getIpAddr(request), point.getTarget().getClass().getSimpleName(), point.getSignature().getName());
+        UserDO sysUser = ShiroUtils.getSysUser();
+        if(Objects.isNull(sysUser)){
+            sysUser = new UserDO();
+        }
+        Long userId = sysUser.getId();
+        String username = sysUser.getUsername();
+
+        if (isLogPretty) {
+            log.info("User request info  ---- {} ---- S", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN_19));
+            log.info("请求接口: {} {}@{} {} {}.{}", request.getMethod(), request.getRequestURI(), userId, IPUtils.getIpAddr(request), point.getTarget().getClass().getSimpleName(), point.getSignature().getName());
             log.info("请求参数:{}", JSONUtils.beanToJson(point.getArgs()));
             log.info("请求耗时:{} ms", time);
-            log.info("请求用户:{} ", ShiroUtils.getUserId());
+            log.info("请求用户:{} [{}]", userId, username);
             log.info("请求结果:{}", JSONUtils.beanToJson(result));
-            log.info("------------------------------------------------ E", DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN_19));
+            log.info("------------------------------------------------ E", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN_19));
         } else {
-            log.info("【请求】:{} {}@{} {} {}.{}{} (耗时 {} ms) 【返回】:{}", request.getMethod(), request.getRequestURI(), ShiroUtils.getUserId(), IPUtils.getIpAddr(request), point.getTarget().getClass().getSimpleName(), point.getSignature().getName(), JSONUtils.beanToJson(point.getArgs()), time, JSONUtils.beanToJson(result));
+            log.info("【请求】:{} {}@{}[{}] {} {}.{}{} (耗时 {} ms) 【返回】:{}", request.getMethod(), request.getRequestURI(), userId, username, IPUtils.getIpAddr(request), point.getTarget().getClass().getSimpleName(), point.getSignature().getName(), JSONUtils.beanToJson(point.getArgs()), time, JSONUtils.beanToJson(result));
         }
     }
 
@@ -88,6 +128,7 @@ public class LogAspect {
      * 保存日志
      * </pre>
      * <small> 2018年3月22日 | Aron</small>
+     *
      * @param joinPoint
      * @param time
      */
@@ -105,31 +146,31 @@ public class LogAspect {
         String methodName = signature.getName();
         String params;
         HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
-        if(request != null) {
-        	sysLog.setMethod(request.getMethod()+" "+request.getRequestURI());
-        	Map<String, String[]> parameterMap = request.getParameterMap();
-        	params = JSONUtils.beanToJson(parameterMap);
-        	// 设置IP地址
-        	sysLog.setIp(IPUtils.getIpAddr(request));
-        }else {
-        	sysLog.setMethod(className + "." + methodName + "()");
-        	Object[] args = joinPoint.getArgs();
-        	params = JSONUtils.beanToJson(args);
+        if (request != null) {
+            sysLog.setMethod(request.getMethod() + " " + request.getRequestURI());
+            Map<String, String[]> parameterMap = request.getParameterMap();
+            params = JSONUtils.beanToJson(parameterMap);
+            // 设置IP地址
+            sysLog.setIp(IPUtils.getIpAddr(request));
+        } else {
+            sysLog.setMethod(className + "." + methodName + "()");
+            Object[] args = joinPoint.getArgs();
+            params = JSONUtils.beanToJson(args);
         }
         int maxLength = 4999;
-        if(params.length() > maxLength){
-        	params = params.substring(0, maxLength);
+        if (params.length() > maxLength) {
+            params = params.substring(0, maxLength);
         }
         sysLog.setParams(params);
         // 用户名
-    	UserDO currUser = ShiroUtils.getSysUser();
-    	if (null == currUser) {
-    		sysLog.setUserId(-1L);
-    		sysLog.setUsername("");
-    	} else {
-    		sysLog.setUserId(currUser.getId());
-    		sysLog.setUsername(currUser.getUsername());
-    	}
+        UserDO currUser = ShiroUtils.getSysUser();
+        if (null == currUser) {
+            sysLog.setUserId(-1L);
+            sysLog.setUsername("");
+        } else {
+            sysLog.setUserId(currUser.getId());
+            sysLog.setUsername(currUser.getUsername());
+        }
         sysLog.setTime((int) time);
         // 系统当前时间
         Date date = new Date();

+ 7 - 19
src/main/java/com/ifast/common/exception/handler/ApplicationExceptionHandler.java

@@ -30,7 +30,7 @@ public class ApplicationExceptionHandler {
      */
     @ExceptionHandler(IllegalArgumentException.class)
     public Result<String> illegalArgumentException(IllegalArgumentException e) {
-        log.error("全局异常处理:IllegalArgumentException[{}]:{}", e.getClass(), e.getMessage());
+        log.info("全局异常处理:IllegalArgumentException[{}]:{}", e.getClass(), e.getMessage());
         return Result.build(EnumErrorCode.illegalArgument.getCode(), e.getMessage());
     }
 
@@ -40,7 +40,7 @@ public class ApplicationExceptionHandler {
     @ExceptionHandler(IFastApiException.class)
     public Result<String> handleIFastAPIException(IFastApiException e) {
         log.info("全局异常处理:IFastApiException[{}]:{}", e.getClass(), e.getMessage());
-        return getStringResult(e.getMessage());
+        return Result.buildByErrorCode(e.getMessage());
     }
 
     /**
@@ -48,42 +48,32 @@ public class ApplicationExceptionHandler {
      */
     @ExceptionHandler(IFastException.class)
     public Object handleIFastException(IFastException e) {
-        log.error("全局异常处理:IFastException[{}]:{}", e.getClass(), e.getMessage());
+        log.info("全局异常处理:IFastException[{}]:{}", e.getClass(), e.getMessage());
         if (!HttpContextUtils.isAjax()) {
             ModelAndView mv = new ModelAndView();
             mv.setViewName(ERROR_DEFAULT_PAGE);
             return mv;
         } else {
-            return getStringResult(e.getMessage());
-        }
-    }
-
-    private Result<String> getStringResult(String message) {
-        try {
-            int code = Integer.parseInt(message);
-            return Result.build(code, EnumErrorCode.getMsgByCode(code));
-        } catch (NumberFormatException e1) {
-            log.warn("错误码使用错误,异常内容请抛出EnumErrorCode类的枚举值");
-            return Result.build(EnumErrorCode.unknowFail.getCode(), EnumErrorCode.unknowFail.getMsg());
+            return Result.buildByErrorCode(e.getMessage());
         }
     }
 
 
     @ExceptionHandler(DuplicateKeyException.class)
     public Result<String> handleDuplicateKeyException(DuplicateKeyException e) {
-        log.error("全局异常处理:DuplicateKeyException[{}]:{}", e.getClass(), e.getMessage());
+        log.info("全局异常处理:DuplicateKeyException[{}]:{}", e.getClass(), e.getMessage());
         return Result.build(EnumErrorCode.duplicateKeyExist.getCode(), EnumErrorCode.duplicateKeyExist.getMsg());
     }
 
     @ExceptionHandler(NoHandlerFoundException.class)
     public Result<String> noHandlerFoundException(NoHandlerFoundException e) {
-        log.error("全局异常处理:NoHandlerFoundException[{}]:{}", e.getClass(), e.getMessage());
+        log.info("全局异常处理:NoHandlerFoundException[{}]:{}", e.getClass(), e.getMessage());
         return Result.build(EnumErrorCode.pageNotFound.getCode(), EnumErrorCode.pageNotFound.getMsg());
     }
 
     @ExceptionHandler(ShiroException.class)
     public Result<String> handleAuthorizationException(ShiroException e) {
-        log.error("全局异常处理:ShiroException[{}][{}]:{}", e.getClass(), e.getClass(), e.getMessage());
+        log.info("全局异常处理:ShiroException[{}][{}]:{}", e.getClass(), e.getClass(), e.getMessage());
         if (e instanceof IncorrectCredentialsException) {
             return Result.build(EnumErrorCode.apiAuthorizationFailed.getCode(), EnumErrorCode.apiAuthorizationFailed.getMsg());
         } else if (e instanceof ExpiredCredentialsException) {
@@ -106,7 +96,5 @@ public class ApplicationExceptionHandler {
         } else {
             return Result.build(EnumErrorCode.unknowFail.getCode(), EnumErrorCode.unknowFail.getMsg());
         }
-
-
     }
 }

+ 2 - 3
src/main/java/com/ifast/common/shiro/cache/SpringCacheWrapper.java

@@ -1,11 +1,10 @@
 package com.ifast.common.shiro.cache;
 
+import lombok.extern.slf4j.Slf4j;
 import net.sf.ehcache.Ehcache;
 import org.apache.shiro.cache.Cache;
 import org.apache.shiro.cache.CacheException;
 import org.apache.shiro.util.CollectionUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.springframework.cache.support.SimpleValueWrapper;
 
 import java.util.*;
@@ -15,8 +14,8 @@ import java.util.*;
  *
  * </pre>
  */
+@Slf4j
 public class SpringCacheWrapper implements Cache {
-    private final static Logger log = LoggerFactory.getLogger(SpringCacheWrapper.class);
     private org.springframework.cache.Cache springCache;
     private boolean isEhcache;
     private Set<Object> keys;

+ 15 - 1
src/main/java/com/ifast/common/utils/Result.java

@@ -1,6 +1,9 @@
 package com.ifast.common.utils;
 
 import com.ifast.common.type.EnumErrorCode;
+import lombok.extern.slf4j.Slf4j;
+
+import java.io.Serializable;
 
 /**
  * <pre>
@@ -11,7 +14,8 @@ import com.ifast.common.type.EnumErrorCode;
  * @author Aron
  * @date 2017年5月9日
  */
-public class Result<T> {
+@Slf4j
+public class Result<T> implements Serializable {
 
     public final static Integer CODE_SUCCESS = EnumErrorCode.success.getCode();
     public final static Integer CODE_FAIL = EnumErrorCode.fail.getCode();
@@ -69,6 +73,16 @@ public class Result<T> {
         return new Result<>(status, msg, data);
     }
 
+    public static Result<String> buildByErrorCode(String errorCode) {
+        try {
+            int code = Integer.parseInt(errorCode);
+            return Result.build(code, EnumErrorCode.getMsgByCode(code));
+        } catch (NumberFormatException e1) {
+            log.warn("错误码使用错误,异常内容请抛出EnumErrorCode类的枚举值");
+            return Result.build(EnumErrorCode.unknowFail.getCode(), EnumErrorCode.unknowFail.getMsg());
+        }
+    }
+
     // get set
 
     public Integer getCode() {