All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.kaizen4j.common.interceptor.MonitorMethodInterceptor Maven / Gradle / Ivy

There is a newer version: 1.3.8.RELEASE
Show newest version
package org.kaizen4j.common.interceptor;

import com.google.common.base.Throwables;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 方法调用监控拦截器。使用示例:
 *
 * 
 * {@code
 *  
 *      
 *  
 *
 * 	
 * 		
 * 	
 * }
 * 
*/ public final class MonitorMethodInterceptor implements MethodInterceptor { private static final Logger logger = LoggerFactory.getLogger(MonitorMethodInterceptor.class); private static final long DEFAULT_WARN_SWITCH_MILLIS = 3 * 1000; private long warnSwitchMillis = DEFAULT_WARN_SWITCH_MILLIS; public void setWarnSwitchMillis(long warnSwitchMillis) { this.warnSwitchMillis = warnSwitchMillis; } @Override public Object invoke(MethodInvocation invocation) throws Throwable { try { StopWatch watcher = new StopWatch(); watcher.start(); Object result = invocation.proceed(); statistic(invocation, result, watcher.getTime()); return result; } catch (Exception e) { logger.error("MonitorMethodInterceptor exception", e); throw new RuntimeException(e); } } private void statistic(MethodInvocation invocation, Object result, long executeTime) { String method = getMethod(invocation); if (logger.isDebugEnabled()) { String args = getArgs(invocation); logger.debug("Method: [{}()] Invocation Arguments: {}", method, args); } if (executeTime > warnSwitchMillis) { logger.warn("Method: [{}()] Invocation is very slowly: [{}] Millis", method, executeTime); } else if (logger.isDebugEnabled()) { logger.debug("Method: [{}()], Invocation Time: [{}] Millis", method, executeTime); } if (logger.isDebugEnabled() && Objects.nonNull(result)) { logger.debug("Method: [{}()] Invocation Result: {}", method, ToStringBuilder.reflectionToString(result, ToStringStyle.MULTI_LINE_STYLE)); } } private String getMethod(MethodInvocation invocation) { return invocation.getMethod().getDeclaringClass().getName() + "." + invocation.getMethod().getName(); } private String getArgs(MethodInvocation invocation) { String args = ""; if (Objects.nonNull(invocation.getArguments())) { args = Arrays.asList(invocation.getArguments()).stream() .map(arg -> ToStringBuilder.reflectionToString(arg, ToStringStyle.MULTI_LINE_STYLE)) .collect(Collectors.joining(",")); } return args; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy