AspectWebLog.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package com.emato.cus.supervise.aop;
  2. import com.fasterxml.jackson.core.JsonProcessingException;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import org.aspectj.lang.JoinPoint;
  5. import org.aspectj.lang.ProceedingJoinPoint;
  6. import org.aspectj.lang.annotation.Aspect;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import java.util.Map;
  10. /**
  11. * Created by Anyx on 2015/5/13.
  12. * 日志AOP
  13. */
  14. @Aspect
  15. public class AspectWebLog {
  16. private static final Logger logger = LoggerFactory.getLogger(AspectWebLog.class);
  17. ObjectMapper mapper = new ObjectMapper();
  18. /**
  19. * 方法开始前执行
  20. * @param jp:JoinPoint
  21. * @return
  22. */
  23. public void beforeAdvice(JoinPoint jp) {
  24. try {
  25. Object[] args = jp.getArgs();
  26. StringBuffer sb = new StringBuffer();
  27. String str = null;
  28. if (args[0] instanceof Map) {
  29. Map<String, String> map = (Map<String, String>) args[0];
  30. str = mapper.writeValueAsString(map);
  31. }else{
  32. str = mapper.writeValueAsString(args[0]);
  33. }
  34. logger.info("入参:{}", str);
  35. } catch (JsonProcessingException e) {
  36. e.printStackTrace();
  37. }
  38. }
  39. /**
  40. * 方法返回后执行
  41. * @param jp:JoinPoint
  42. * @param retValue:String 主体方法传递到通知方法的返回值
  43. * @return
  44. */
  45. public void afterReturningAdvice(JoinPoint jp, String retValue) {
  46. logger.info("出参:{}",retValue);
  47. }
  48. /**
  49. * 方法异常后执行
  50. * @param jp:JoinPoint
  51. * @return
  52. */
  53. public void afterThrowingAdvice(JoinPoint jp) {
  54. logger.info("异常结束后:{}");
  55. }
  56. /**
  57. * 方法完后执行,无论成功还是异常
  58. * @param jp:JoinPoint
  59. * @return
  60. */
  61. public void afterAdvice(JoinPoint jp) {
  62. logger.info("执行结束后:{}");
  63. }
  64. /**
  65. * 主体方法返回后将执行的通知方法
  66. * @param pjp:ProceedingJoinPoint
  67. * @return
  68. */
  69. public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
  70. long bftime = System.currentTimeMillis();
  71. Object retVal = pjp.proceed();
  72. double time =(double)(System.currentTimeMillis() - bftime) / 1000;
  73. logger.debug("执行时间:{}秒", time);
  74. return retVal;
  75. }
  76. }