/** * 处理登陆日志 * @param joinPoint * @param proceed */ private void handlerLoginLog(ProceedingJoinPoint joinPoint,Object proceed) { Signature signature = joinPoint.getSignature(); //是登陆操作 if(signature.getDeclaringTypeName().equals("com.lovecws.mumu.system.controller.system.index.SysLoginController")&&signature.getName().equals("logining")){ //登陆成功 if(proceed instanceof ModelAndView){ ModelAndView modelAndView=(ModelAndView)proceed; Map<String, Object> model = modelAndView.getModel(); Object code = model.get("code"); if(code!=null&&"200".equals(code.toString())){ messageHandler.handler(); } } } }
/** * Monitor the elapsed time of method on controller layer, in * order to detect performance problems as soon as possible. * If elapsed time > 1 s, log it as an error. Otherwise, log it * as an info. */ @Around("controllerLayer()") public Object monitorElapsedTime(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { // Timing the method in controller layer StopWatch stopWatch = new StopWatch(); stopWatch.start(); Object result = proceedingJoinPoint.proceed(); stopWatch.stop(); // Log the elapsed time double elapsedTime = stopWatch.getTime() / 1000.0; Signature signature = proceedingJoinPoint.getSignature(); String infoString = "[" + signature.toShortString() + "][Elapsed time: " + elapsedTime + " s]"; if (elapsedTime > 1) { log.error(infoString + "[Note that it's time consuming!]"); } else { log.info(infoString); } // Return the result return result; }
@AfterThrowing(throwing = "ex", pointcut = "execution(* com.github.izhangzhihao.SSMSeedProject.*.*.*(..)))") public void LogToDB(JoinPoint joinPoint, Throwable ex) { //出错行 int lineNumber = ex.getStackTrace()[0].getLineNumber(); //方法签名 Signature signature = joinPoint.getSignature(); //参数 Object[] args = joinPoint.getArgs(); //拼接参数 StringBuilder argString = new StringBuilder(); if (args.length > 0) for (Object arg : args) argString.append(arg); ex.printStackTrace(); log.error("方法" + signature, "参数" + argString, "错误行:" + lineNumber, "时间" + new Date(), "异常内容" + ex.toString()); }
@Around("monitored()") public Object requestMapping(final ProceedingJoinPoint pcp) throws Throwable { Signature signature = pcp.getSignature(); if (signature instanceof MethodSignature) { Method method = ((MethodSignature) signature).getMethod(); MethodProfiling annotation = AnnotationUtils.findAnnotation(method, MethodProfiling.class); if (annotation == null) { annotation = AnnotationUtils.findAnnotation(pcp.getTarget().getClass(), MethodProfiling.class); } if (annotation != null) { return traceMethodCall(pcp, annotation.logCallStatistics(), annotation.logMethodCall(), annotation.maxToStringLength()); } } return traceMethodCall(pcp); }
@After("execution(* *..web..*Controller.*(..))") // 在方法执行之后执行的代码. 无论该方法是否出现异常 public void afterMethod(JoinPoint jp) { Signature signature = jp.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method targetMethod = methodSignature.getMethod(); //Class<? extends Method> clazz = targetMethod.getClass(); if(record){ if(targetMethod.getAnnotation(LogAudit.class) != null){ saveOperateLog(targetMethod); } else if(baseControllerMethodNames.contains(targetMethod.getName())){ Method parentMethod = baseControllerMethods.get(targetMethod.getName()); if(parentMethod.getAnnotation(LogAudit.class) != null){ saveOperateLog(targetMethod); } } } }
@Nullable private static JoinPointDescription generateCacheKey(ProceedingJoinPoint proceedingJoinPoint) { String className; String returnType; String methodName; Signature signature = proceedingJoinPoint.getSignature(); if (signature instanceof MethodSignature) { MethodSignature methodSignature = (MethodSignature) signature; returnType = methodSignature.getReturnType().getCanonicalName(); methodName = methodSignature.getName(); className = methodSignature.getDeclaringTypeName(); } else { return null; } return new JoinPointDescription(className, methodName, returnType, proceedingJoinPoint.getArgs()); }
@Around("set(* (@com.lib.logthisannotations.annotation.LogThisClassFields *) . *) && args(newVal) && target(t) ") public void aroundSetField(ProceedingJoinPoint jp, Object t, Object newVal) throws Throwable{ Logger logger = Logger.getInstance(); if(logger != null) { Signature signature = jp.getSignature(); String fieldName = signature.getName(); Field field = t.getClass().getDeclaredField(fieldName); field.setAccessible(true); Object oldVal = field.get(t); LogThisClassFields annotation = t.getClass().getAnnotation(LogThisClassFields.class); LoggerLevel loggerLevel = annotation.logger(); StringBuilder builder = Strings.getStringFieldBuilder(fieldName, String.valueOf(oldVal), String.valueOf(newVal)); logger.getLoggerInstance().log(t.getClass().getName(), "ClassField " + builder.toString(), loggerLevel, annotation.write()); jp.proceed(); } }
private static void exitMethod(JoinPoint joinPoint, Object result, long lengthMillis) { if (!enabled) return; Signature signature = joinPoint.getSignature(); Class<?> cls = signature.getDeclaringType(); String methodName = signature.getName(); boolean hasReturnType = signature instanceof MethodSignature && ((MethodSignature) signature).getReturnType() != void.class; StringBuilder builder = new StringBuilder("\u21E0 ") .append(methodName) .append(" [") .append(lengthMillis) .append("ms]"); if (hasReturnType) { builder.append(" = "); builder.append(Strings.toString(result)); } // TODO : use a real Logger System.out.println(asTag(cls) + " : " + builder.toString()); }
private void exit(JoinPoint joinPoint, Object result, StringBuilder builder) { if (!enabled) return; Signature signature = joinPoint.getSignature(); Class<?> cls = signature.getDeclaringType(); boolean hasReturnType = signature instanceof MethodSignature && ((MethodSignature) signature).getReturnType() != void.class; if (hasReturnType) { builder.append(" \u21a6 "); builder.append(Strings.toString(result)); } Log.v(asTag(cls), builder.toString()); }
@Before("methodWithBatchSizeCheck()") public void checkBatchSize(JoinPoint joinPoint) throws NoSuchMethodException { Signature signature = joinPoint.getSignature(); if (!(signature instanceof MethodSignature)) { return; } // must use target since the annotation is annotated on the impl, not api Method method = joinPoint.getTarget().getClass().getMethod(signature.getName(), ((MethodSignature) signature).getParameterTypes()); if (method == null || !method.isAnnotationPresent(RestrictBatchSize.class)) { return; } RestrictBatchSize restrictBatchSize = method.getAnnotation(RestrictBatchSize.class); int paramIndex = restrictBatchSize.paramIndex(); if (paramIndex < 0) { return; } int batchSize = (Integer) (joinPoint.getArgs())[paramIndex]; checkArgument(batchSize <= ConstantsUtil.MaxBatchSize(), String.format("Batch size(%d) exceeds max allowed size: %d", batchSize, ConstantsUtil.MaxBatchSize())); }
public static void trackFragmentView(JoinPoint joinPoint, Object result) { try { Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method targetMethod = methodSignature.getMethod(); if (targetMethod == null) { return; } //Fragment名称 String fragmentName = joinPoint.getTarget().getClass().getName(); if (result instanceof ViewGroup) { traverseView(fragmentName, (ViewGroup) result); } else if (result instanceof View) { View view = (View) result; view.setTag(R.id.sensors_analytics_tag_view_fragment_name, fragmentName); } } catch (Exception e) { e.printStackTrace(); } }
@Test public void testLogAfterThrowing() { // Arrange JoinPoint joinPoint = Mockito.mock(JoinPoint.class); Signature signature = Mockito.mock(Signature.class); when(joinPoint.getSignature()).thenReturn(signature); when(signature.getDeclaringTypeName()).thenReturn("Declaring Type Name"); when(signature.getName()).thenReturn("Name"); Exception exception = Mockito.mock(Exception.class); when(exception.getCause()).thenReturn(Mockito.mock(Throwable.class)); // Act this.loggingAspect.logAfterThrowing(joinPoint, exception); // Assert assertThat(this.loggingAspect, not(nullValue())); }
@Around("loggingPointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { Signature signature = joinPoint.getSignature(); if (log.isDebugEnabled()) { log.debug("Enter: {}.{}() with argument[s] = {}", signature.getDeclaringTypeName(), signature.getName(), Arrays.toString(joinPoint.getArgs())); } try { Object result = joinPoint.proceed(); if (log.isDebugEnabled()) { log.debug("Exit: {}.{}() with result = {}", signature.getDeclaringTypeName(), signature.getName(), result); } return result; } catch (IllegalArgumentException e) { log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()), signature.getDeclaringTypeName(), signature.getName()); throw e; } }
@Test public void testDetermineDelay() throws Exception { BaseActionLoader loader = BeanLoader.loadBaseActionLoader(); when(loader.getSahiProxyProperties().getRequestDelayMs()).thenReturn(500); loader.getActionProperties().setTypeDelay(0.05); JoinPoint joinPoint = mock(JoinPoint.class); Signature signature = mock(Signature.class); when(joinPoint.getSignature()).thenReturn(signature); when(signature.getName()).thenReturn("pasteSomething"); assertEquals(testling.determineDelay(joinPoint, loader).intValue(), 500); when(signature.getName()).thenReturn("typeMasked"); when(joinPoint.getArgs()).thenReturn(new String[]{"1", "MOD"}); assertEquals(testling.determineDelay(joinPoint, loader).intValue(), 550); when(joinPoint.getArgs()).thenReturn(new String[]{"12characters", "MOD"}); assertEquals(testling.determineDelay(joinPoint, loader).intValue(), 12 * 550); }
private static Annotation getAnnotation(final Signature signature, final Class<? extends Annotation> annotationClass) { if (signature instanceof ConstructorSignature) { final Constructor<?> ctor = ConstructorSignature.class.cast(signature) .getConstructor(); return ctor.getAnnotation(annotationClass); } else if (signature instanceof MethodSignature) { return MethodSignature.class.cast(signature) .getMethod() .getAnnotation(annotationClass); } else if (signature instanceof FieldSignature) { return FieldSignature.class.cast(signature) .getField() .getAnnotation(annotationClass); } throw new RuntimeException( "Unsupported signature type " + signature.getClass().getName() ); }
@Test public void should_return_for_method_for_valid_proceedingoinpoint() { ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); Signature signature = Mockito.mock(Signature.class); Mockito.when(proceedingJoinPoint.getSignature()).thenReturn(signature); Mockito.when(signature.getName()).thenReturn(METHOD.getName()); AspectjProceedingJoinPointContextProvider givenAspectjProceedingJoinPointContextProvider = new AspectjProceedingJoinPointContextProvider(); givenAspectjProceedingJoinPointContextProvider.setContextData(proceedingJoinPoint); String result = givenAspectjProceedingJoinPointContextProvider.getMethod(); MatcherAssert.assertThat(result, Matchers.notNullValue()); MatcherAssert.assertThat(result, Matchers.equalTo(METHOD.getName())); }
public static Map<String, Object> getJoinPointContextMap(JoinPoint jp) { Map<String, Object> context = new HashMap<String, Object>(); context.put("_jp", jp); // convenience binding context.put("_this", jp.getThis()); context.put("_target", jp.getTarget()); context.put("_args", jp.getArgs()); Signature sig = jp.getSignature(); if (sig instanceof CodeSignature) { CodeSignature codeSig = (CodeSignature) sig; String[] paramNames = codeSig.getParameterNames(); Object[] args = jp.getArgs(); for (int i = 0; i < paramNames.length; i++) { context.put(paramNames[i], args[i]); } } return context; }
public void beforeTrans(JoinPoint point) { Signature signature = point.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); // 获取目标类 Class<?> target = point.getTarget().getClass(); Method targetMethod = null; try { targetMethod = target.getMethod(method.getName(), method.getParameterTypes()); } catch (NoSuchMethodException e) { e.printStackTrace(); } // 根据目标类方法中的注解,选择数据源 if (targetMethod != null) { Transactional transactional = targetMethod.getAnnotation(Transactional.class); if (transactional != null) { SpecifyDS specifyDSCls = target.getAnnotation(SpecifyDS.class); SpecifyDS specifyDS = targetMethod.getAnnotation(SpecifyDS.class); if (specifyDS != null) { DataSourceHolder.setDataSource(specifyDS.value()); } else if (specifyDSCls != null) { DataSourceHolder.setDataSource(specifyDSCls.value()); } else { DataSourceHolder.setDataSource(defaultTransDb); } } } }
@Override public Signature getSignature() { if (this.signature == null) { this.signature = new MethodSignatureImpl(); } return signature; }
/** * To string string. * * @param jp the jp * @return the string */ public static String toString(JoinPoint jp) { StringBuilder sb = new StringBuilder(); appendType(sb, getType(jp)); Signature signature = jp.getSignature(); if (signature instanceof MethodSignature) { MethodSignature ms = (MethodSignature) signature; sb.append("#"); sb.append(ms.getMethod().getName()); sb.append("("); appendTypes(sb, ms.getMethod().getParameterTypes()); sb.append(")"); } return sb.toString(); }
public DefaultRequestCacheKey(ProceedingJoinPoint point) throws NoSuchMethodException { Object[] args = point.getArgs(); Signature signature = point.getSignature(); if (!(signature instanceof MethodSignature)) { throw new IllegalArgumentException("该注解只能用于方法"); } MethodSignature methodSignature = (MethodSignature) signature; Object target = point.getTarget(); Method currentMethod = target.getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes()); clazzKey = currentMethod.getDeclaringClass().getName(); methodKey = currentMethod.getName(); Class[] parameterTypes = methodSignature.getParameterTypes(); StringBuilder builderParamKey = new StringBuilder(); StringBuilder builderValueKey = new StringBuilder(); if (parameterTypes != null) { for (int i = 0; i < parameterTypes.length; i++) { if (i != 0) { builderParamKey.append("#"); builderValueKey.append("#"); } builderParamKey.append(parameterTypes[i].getName()); builderValueKey.append(args[i]); } } paramKey = builderParamKey.toString(); valueKey = builderValueKey.toString(); }
/** * Monitor whether exception is thrown in service layer. If exception * has been thrown, in order to detecting it conveniently, log the * situation where it happened. Then create a server internal error * exception and throw it out. */ @AfterThrowing(pointcut = "com.wind.monitor.ServiceMonitor.serviceLayer()", throwing = "e") public void monitorException(JoinPoint joinPoint, Throwable e) { // Log the situation where exception happened Object[] args = joinPoint.getArgs(); Signature signature = joinPoint.getSignature(); log.error("[" + signature.toShortString() + "]" + Arrays.toString(args) + "[" + e.toString() + "]"); // Throw a new server internal error exception throw new ServerInternalErrorException(); }
private LimitIPRequestAnnotation getAnnotation(JoinPoint joinPoint) { Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); if (method != null) { return method.getAnnotation(LimitIPRequestAnnotation.class); } return null; }
/** * Before. * 前置通知 * @param joinPoint the join point */ @Before("pointcut()") public void before(JoinPoint joinPoint){ Signature signature=joinPoint.getSignature(); // Object[] o = joinPoint.getArgs(); // for (Object o1: o // ) { // System.out.println(o1.toString()); // } logger.info("--------before execute method,method name is:'"+signature.getDeclaringType()+"."+signature.getName()+"'"); }
public static void initDadesAdvice(Signature signature) { DadesAdvice dadesAdvice = dadesAdviceThreadLocal.get(); if (dadesAdvice == null) dadesAdvice = new DadesAdvice(); if (dadesAdvice.getSignature() == null) { dadesAdvice.setSignature(signature); dadesAdviceThreadLocal.set(dadesAdvice); } }
@Before("execution(* net.conselldemallorca.helium.core.model.service.ExpedientService*.*(..)) " + "|| execution(* net.conselldemallorca.helium.core.model.service.TascaService*.*(..)) " + "|| execution(* net.conselldemallorca.helium.v3.core.service.ExpedientService*.*(..)) " + "|| execution(* net.conselldemallorca.helium.v3.core.service.TascaService*.*(..)) " + "|| execution(* net.conselldemallorca.helium.jbpm3.spring.SpringJobExecutorThread.executeJob(..))") public void before(JoinPoint joinPoint) { Signature signature = joinPoint.getSignature(); initDadesAdvice(signature); }
/** * Called between the throw and the catch */ // TODO: Para la interficie v.3 cambiar a net.conselldemallorca.helium.v3.core.service @AfterThrowing(pointcut = "execution(* net.conselldemallorca.helium.core.model.service.ExpedientService*.*(..)) " + "|| execution(* net.conselldemallorca.helium.core.model.service.TascaService*.*(..)) " + "|| execution(* net.conselldemallorca.helium.v3.core.service.ExpedientService*.*(..)) " + "|| execution(* net.conselldemallorca.helium.v3.core.service.TascaService*.*(..))", throwing = "e") public void afterThrowing(JoinPoint joinPoint, Throwable e) { Signature signature = joinPoint.getSignature(); if (!getDadesAdvice().getIdsPortasignatures().isEmpty()) { Jbpm3HeliumBridge.getInstanceService().portasignaturesEliminar(getDadesAdvice().getIdsPortasignatures()); } clearDadesAdvice(signature); }
@AfterReturning("execution(* net.conselldemallorca.helium.core.model.service.ExpedientService*.*(..)) " + "|| execution(* net.conselldemallorca.helium.core.model.service.TascaService*.*(..)) " + "|| execution(* net.conselldemallorca.helium.v3.core.service.ExpedientService*.*(..)) " + "|| execution(* net.conselldemallorca.helium.v3.core.service.TascaService*.*(..)) " + "|| execution(* net.conselldemallorca.helium.jbpm3.spring.SpringJobExecutorThread.executeJob(..))") public void after(JoinPoint joinPoint) { Signature signature = joinPoint.getSignature(); clearDadesAdvice(signature); }
public void ErrorLog(JoinPoint joinPoint, Throwable ex){ //出错行 int lineNumber = ex.getStackTrace()[0].getLineNumber(); //j Signature signature = joinPoint.getSignature(); //参数 Object[] args = joinPoint.getArgs(); //拼接参数 StringBuilder argString = new StringBuilder(); if (args.length > 0) for (Object arg : args) argString.append(arg); log.error("方法" + signature, "参数" + argString, "错误行:" + lineNumber, "时间" + new Date(), "异常内容" + ex.toString()); }
/** * Monitor whether exception is thrown in service layer. If exception * has been thrown, in order to detecting it conveniently, log the * situation where it happened. Then create a server internal error * exception and throw it out. */ @AfterThrowing(pointcut = "com.shawn.monitor.ServiceMonitor.serviceLayer()", throwing = "e") public void monitorException(JoinPoint joinPoint, Throwable e) { // Log the situation where exception happened Object[] args = joinPoint.getArgs(); Signature signature = joinPoint.getSignature(); log.error("[" + signature.toShortString() + "]" + Arrays.toString(args) + "[" + e.toString() + "]"); // Throw a new server internal error exception throw new ServerInternalErrorException(); }
@AfterThrowing(throwing = "ex", pointcut = "execution(* com.github.izhangzhihao.SpringMVCSeedProject.*.*.*(..)))") public void LogToDB(JoinPoint joinPoint, Throwable ex) { //出错行 int lineNumber = ex.getStackTrace()[0].getLineNumber(); //方法签名 Signature signature = joinPoint.getSignature(); //参数 Object[] args = joinPoint.getArgs(); //拼接参数 StringBuilder argString = new StringBuilder(); if (args.length > 0) for (Object arg : args) argString.append(arg); log.error("方法" + signature, "参数" + argString, "错误行:" + lineNumber, "时间" + new Date(), "异常内容" + ex.toString()); }
private void logMethodCall(Logger logger, Signature signature, Object[] args, Object result, int maxReturnLength) { MethodSignature methodSignature = (MethodSignature) signature; String method = methodSignature.getMethod().getDeclaringClass().getSimpleName() + "." + methodSignature.getMethod().getName(); logger.trace("{}({}){}", method, formatArguments(args, maxReturnLength), formatResult(signature.getDeclaringType(), result, maxReturnLength) ); }
@AfterThrowing(pointcut = "anyMethodCall(joinPoint)", throwing = "exception") public void afterAnyMethodThrowingException(JoinPoint joinPoint, Throwable exception) { if (log.isDebugEnabled()) { log.debug("aspect start: afterAnyMethodThrowingException"); } Signature signature = joinPoint.getSignature(); String className = signature.getDeclaringTypeName(); String methodName = signature.getName(); String arguments = Arrays.toString(joinPoint.getArgs()); StackTraceElement[] stackTrace = exception.getStackTrace(); if (stackTrace.length == 0 || !methodName.equals(stackTrace[0].getMethodName()) || !className.equals(stackTrace[0].getClassName())) { return; } if (log.isDebugEnabled()) { log.debug("We have caught exception in method: " + methodName + " with arguments " + arguments + "\nand the full toString: " + "\nthe exception is: " + exception.toString()); } ExceptionInfo exceptionInfo = new ExceptionInfo() .setException(exception) .setName(exception.getClass().toString()) .setClassName(className) .setFileName(stackTrace[0].getFileName()) .setLineNumber(stackTrace[0].getLineNumber()) .setMethodName(methodName) .setArguments(Arrays.asList(joinPoint.getArgs())); ExceptionEventPublisher exceptionEventPublisher = new ExceptionEventPublisher(); exceptionEventPublisher.publishEvent(exceptionInfo); }
/** * 获取拦截的方法 * @param jp * @return */ public static Method getMethod(JoinPoint jp) { Signature signature = jp.getSignature(); if(signature instanceof MethodSignature){ MethodSignature methodSignature = (MethodSignature) signature; return methodSignature.getMethod(); } return null; }
@Around("@annotation(com.mogujie.trade.db.ReadWriteSplitting)") public Object intercept(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { Signature signature = proceedingJoinPoint.getSignature(); DataSourceType dataSourceType = null; if (signature instanceof MethodSignature) { // 若已经在事务中 则不做处理 if (RoutingDataSourceTransactionContext.getCurTransactionDataSource() != null) { return proceedingJoinPoint.proceed(); } // 若已经设置为Master 则忽略 if (ReadWriteSplittingContext.isMaster()) { return proceedingJoinPoint.proceed(); } MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); dataSourceType = this.getDataSourceType(method); } else { // this may not happend. throw new ReadWriteSplittingException("ReadWriteSplitting annotation should only used on method. "); } ReadWriteSplittingContext.set(dataSourceType); logger.debug("{} {} using dataSourceOf {} ", proceedingJoinPoint.getTarget(), proceedingJoinPoint.getSignature(), dataSourceType); try { return proceedingJoinPoint.proceed(); } finally { ReadWriteSplittingContext.clear(); logger.debug("{} release dataSource of {}", proceedingJoinPoint.getTarget(), dataSourceType); } }