a99a97d0a6fe99dfb799ad9f395f0a8ec7cd3f8d
[sdc.git] /
1 /*
2  * Copyright © 2016-2017 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdc.logging.aspects;
18
19 import org.aspectj.lang.ProceedingJoinPoint;
20 import org.aspectj.lang.annotation.Around;
21 import org.aspectj.lang.annotation.Aspect;
22 import org.openecomp.sdc.logging.api.Logger;
23 import org.openecomp.sdc.logging.api.LoggerFactory;
24 import org.openecomp.sdc.logging.api.annotations.Metrics;
25
26 /**
27  * <p>Wraps around any method annotated with {@link Metrics} to measure and log its execution time
28  * in milliseconds.</p>
29  * <p>In order for the aspect to be used, AspectJ annotation processing must be tuned on and this
30  * particular aspect enabled. Conversely, it can be disabled completely if the application does not
31  * need to log metrics.</p>
32  * <p>See, for example, <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html">
33  * Aspect Oriented Programming with Spring</a>.</p>
34  *
35  * @author evitaliy
36  * @see Metrics
37  * @since 27/07/2016.
38  */
39 @Aspect
40 public class MetricsAspect {
41
42   private static final String MESSAGE_TEMPLATE = "'{}' took {} milliseconds";
43
44   @Around("@annotation(org.openecomp.sdc.logging.api.annotations.Metrics)")
45   public Object logExecutionTime(ProceedingJoinPoint pjp) throws Throwable {
46
47     final Logger logger = LoggerFactory.getLogger(pjp.getSignature().getDeclaringTypeName());
48     // measure and log only if the logger for this class is enabled
49     if (logger.isMetricsEnabled()) {
50
51       final String method = pjp.getSignature().getName();
52       final long start = System.currentTimeMillis();
53
54       try {
55         return pjp.proceed();
56       } finally {
57         logger.metrics(MESSAGE_TEMPLATE, method, System.currentTimeMillis() - start);
58       }
59
60     } else {
61       return pjp.proceed();
62     }
63   }
64 }