fix: 日志切面中ThreadLocal可能引发的内存泄漏

pull/787/head
snow 2023-02-08 19:46:15 +08:00
parent f3cdf8ccfc
commit 8bd547e79d
1 changed files with 13 additions and 8 deletions

View File

@ -29,6 +29,7 @@ import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
/** /**
@ -65,11 +66,15 @@ public class LogAspect {
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object result; Object result;
currentTime.set(System.currentTimeMillis()); currentTime.set(System.currentTimeMillis());
result = joinPoint.proceed(); Log log;
Log log = new Log("INFO",System.currentTimeMillis() - currentTime.get()); try {
currentTime.remove(); result = joinPoint.proceed();
log = new Log("INFO", System.currentTimeMillis() - currentTime.get());
} finally {
currentTime.remove();
}
HttpServletRequest request = RequestHolder.getHttpServletRequest(); HttpServletRequest request = RequestHolder.getHttpServletRequest();
logService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request),joinPoint, log); logService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request), joinPoint, log);
return result; return result;
} }
@ -77,21 +82,21 @@ public class LogAspect {
* *
* *
* @param joinPoint join point for advice * @param joinPoint join point for advice
* @param e exception * @param e exception
*/ */
@AfterThrowing(pointcut = "logPointcut()", throwing = "e") @AfterThrowing(pointcut = "logPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
Log log = new Log("ERROR",System.currentTimeMillis() - currentTime.get()); Log log = new Log("ERROR", System.currentTimeMillis() - currentTime.get());
currentTime.remove(); currentTime.remove();
log.setExceptionDetail(ThrowableUtil.getStackTrace(e).getBytes()); log.setExceptionDetail(ThrowableUtil.getStackTrace(e).getBytes());
HttpServletRequest request = RequestHolder.getHttpServletRequest(); HttpServletRequest request = RequestHolder.getHttpServletRequest();
logService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request), (ProceedingJoinPoint)joinPoint, log); logService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request), (ProceedingJoinPoint) joinPoint, log);
} }
public String getUsername() { public String getUsername() {
try { try {
return SecurityUtils.getCurrentUsername(); return SecurityUtils.getCurrentUsername();
}catch (Exception e){ } catch (Exception e) {
return ""; return "";
} }
} }