2012-08-09 71 views

回答

2

您可以使用Spring框架的PerformanceMonitorInterceptor來記錄方法條目。 Here是DZone的示例用法。

4

可以使用@Around(..)用於這樣的目的方面:

@Component 
@Aspect 
@Order(value=2) 
public class LoggingAspect { 

    @Around("execution(* com.blablabla.server..*.*(..))") 
    public Object logMethod(ProceedingJoinPoint joinPoint) throws Throwable{ 
     final Logger logger = LoggerFactory.getLogger(joinPoint.getTarget().getClass().getName()); 
     Object retVal = null; 

     try { 
      StringBuffer startMessageStringBuffer = new StringBuffer(); 

      startMessageStringBuffer.append("Start method "); 
      startMessageStringBuffer.append(joinPoint.getSignature().getName()); 
      startMessageStringBuffer.append("("); 

      Object[] args = joinPoint.getArgs(); 
      for (int i = 0; i < args.length; i++) { 
       startMessageStringBuffer.append(args[i]).append(","); 
      } 
      if (args.length > 0) { 
       startMessageStringBuffer.deleteCharAt(startMessageStringBuffer.length() - 1); 
      } 

      startMessageStringBuffer.append(")"); 

      logger.trace(startMessageStringBuffer.toString()); 

      StopWatch stopWatch = new StopWatch(); 
      stopWatch.start(); 

      retVal = joinPoint.proceed(); 

      stopWatch.stop(); 

      StringBuffer endMessageStringBuffer = new StringBuffer(); 
      endMessageStringBuffer.append("Finish method "); 
      endMessageStringBuffer.append(joinPoint.getSignature().getName()); 
      endMessageStringBuffer.append("(..); execution time: "); 
      endMessageStringBuffer.append(stopWatch.getTotalTimeMillis()); 
      endMessageStringBuffer.append(" ms;"); 

      logger.trace(endMessageStringBuffer.toString()); 
     } catch (Throwable ex) { 
      StringBuffer errorMessageStringBuffer = new StringBuffer(); 

      // Create error message 
      logger.error(errorMessageStringBuffer.toString(), e) 

      throw ex; 
     } 

     return retVal; 
    } 
} 

在圍繞方面記錄此示例中,所有方法調用下com.blablabla.server包中的所有的子包。它還記錄所有方法輸入參數。