How to log the time taken by methods in Springframework?

前端 未结 5 1776
时光说笑
时光说笑 2021-01-31 06:20

Is it possible in springframework to log the time taken by methods [ selective | all ] automatically. By automatically i mean, i don\'t want to go to each method and write the l

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-31 07:07

    AOP is what you need here. AOP allows you to add code to your application without modifying the original code. Spring AOP prefers to accomplish this with Proxy objects. Proxy objects use a Decorator Pattern to wrap the original Target object and add code. The Proxy is configured to implement one or more interfaces of the original Target object.

    Here, to time an application, the idea is to use the PerformanceMonitorInterceptor, one of the performance monitoring classes that ship with the Spring Framework.

    The first option is to use the Spring class ProxyFactoryBean to create Spring AOP Proxy objects. To do this:

    • Define your original bean:
    • Define a PerformanceMonitorInterceptor:
    • Define a RegexpMethodPointcutAdvisor:
    • Define a ProxyFactoryBean to proxy your original bean and apply your Advisor
    • Set the Log level for the PerformanceMonitorInterceptor to TRACE

    Below a Spring configuration that illustrates these steps:

    
      
        
      
    
      
    
      
        
        
          
            .*
          
        
      
    
      
        
          org.myapp.services.MyService
        
        
        
          
            timingAdvisor
          
        
      
    
    

    And the configuration of the Log level for the PerformanceMonitorInterceptor:

    log4j.logger.org.springframework.aop.interceptor.PerformanceMonitorInterceptor=TRACE
    

    Starting with Spring 2.0, there is another option: using Spring 2.0 XML Schema-based configuration and Spring's AspectJ style pointcut expressions. With the ProxyFactoryBean you have to explicitly declare the interfaces you want to proxy; using the and tags, you can automatically proxy every interface of every object in the bean container.

    
      
        
      
    
      
    
      
        
      
    
    

提交回复
热议问题