Debian Codegraph @

src/main/java/com/jcabi/aspects/aj/MethodLogger.java

raw
1 /**
2 * Copyright (c) 2012-2017, jcabi.com
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met: 1) Redistributions of source code must retain the above
8 * copyright notice, this list of conditions and the following
9 * disclaimer. 2) Redistributions in binary form must reproduce the above
10 * copyright notice, this list of conditions and the following
11 * disclaimer in the documentation and/or other materials provided
12 * with the distribution. 3) Neither the name of the jcabi.com nor
13 * the names of its contributors may be used to endorse or promote
14 * products derived from this software without specific prior written
15 * permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
19 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21 * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
22 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
28 * OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30 package com.jcabi.aspects.aj;
31
32 import com.jcabi.aspects.Loggable;
33 import com.jcabi.log.Logger;
34 import com.jcabi.log.VerboseRunnable;
35 import java.lang.reflect.Method;
36 import java.util.Set;
37 import java.util.concurrent.ConcurrentSkipListSet;
38 import java.util.concurrent.Executors;
39 import java.util.concurrent.FutureTask;
40 import java.util.concurrent.ScheduledExecutorService;
41 import java.util.concurrent.TimeUnit;
42 import java.util.concurrent.atomic.AtomicInteger;
43 import org.aspectj.lang.ProceedingJoinPoint;
44 import org.aspectj.lang.annotation.Around;
45 import org.aspectj.lang.annotation.Aspect;
46 import org.aspectj.lang.reflect.MethodSignature;
47
48 /**
49 * Logs method calls.
50 *
51 * <p>It is an AspectJ aspect and you are not supposed to use it directly. It
52 * is instantiated by AspectJ runtime framework when your code is annotated
53 * with {@link Loggable} annotation.
54 *
55 * @author Yegor Bugayenko ([email protected])
56 * @version $Id: 75ee92b1645b4e6b0a06b21951bf2d3846430588 $
57 * @since 0.7.2
58 * @checkstyle IllegalThrows (500 lines)
59 */
60 @Aspect
61 @SuppressWarnings
62 (
63 {
64 "PMD.AvoidCatchingThrowable",
65 "PMD.TooManyMethods",
66 "PMD.CyclomaticComplexity"
67 }
68 )
69 public final class MethodLogger {
70
71 /**
72 * Currently running methods.
73 */
74 private final transient Set<Marker> running;
75
76 /**
77 * Public ctor.
78 */
79 @SuppressWarnings("PMD.DoNotUseThreads")
80 public MethodLogger() {
81 this.running = new ConcurrentSkipListSet<Marker>();
82 final ScheduledExecutorService monitor =
83 Executors.newSingleThreadScheduledExecutor(
84 new NamedThreads(
85 "loggable",
86 "watching of @Loggable annotated methods"
87 )
88 );
89 monitor.scheduleWithFixedDelay(
90 new FutureTask<Void>(
91 new VerboseRunnable(
92 new Runnable() {
93 @Override
94 public void run() {
95 for (final MethodLogger.Marker marker
96 : MethodLogger.this.running) {
97 marker.monitor();
98 }
99 }
100 }
101 ), null
102 ) {
103 @Override
104 protected void done() {
105 Logger.debug(this, "Logging monitor thread interrupted");
106 monitor.shutdown();
107 }
108 },
109 1, 1, TimeUnit.SECONDS
110 );
111 }
112
113 /**
114 * Log methods in a class.
115 *
116 * <p>Try NOT to change the signature of this method, in order to keep
117 * it backward compatible.
118 *
119 * @param point Joint point
120 * @return The result of call
121 * @throws Throwable If something goes wrong inside
122 */
123 @Around
124 (
125 // @checkstyle StringLiteralsConcatenation (7 lines)
126 "execution(public * (@com.jcabi.aspects.Loggable *).*(..))"
127 + " && !execution(String *.toString())"
128 + " && !execution(int *.hashCode())"
129 + " && !execution(boolean *.canEqual(Object))"
130 + " && !execution(boolean *.equals(Object))"
131 + " && !cflow(call(com.jcabi.aspects.aj.MethodLogger.new()))"
132 )
133 public Object wrapClass(final ProceedingJoinPoint point) throws Throwable {
134 final Method method =
135 MethodSignature.class.cast(point.getSignature()).getMethod();
136 Object output;
137 if (method.isAnnotationPresent(Loggable.class)) {
138 output = point.proceed();
139 } else {
140 output = this.wrap(
141 point,
142 method,
143 method.getDeclaringClass().getAnnotation(Loggable.class)
144 );
145 }
146 return output;
147 }
148
149 /**
150 * Log individual methods.
151 *
152 * <p>Try NOT to change the signature of this method, in order to keep
153 * it backward compatible.
154 *
155 * @param point Joint point
156 * @return The result of call
157 * @throws Throwable If something goes wrong inside
158 */
159 @Around
160 (
161 // @checkstyle StringLiteralsConcatenation (2 lines)
162 "(execution(* *(..)) || initialization(*.new(..)))"
163 + " && @annotation(com.jcabi.aspects.Loggable)"
164 )
165 @SuppressWarnings("PMD.AvoidCatchingThrowable")
166 public Object wrapMethod(final ProceedingJoinPoint point) throws Throwable {
167 final Method method =
168 MethodSignature.class.cast(point.getSignature()).getMethod();
169 return this.wrap(point, method, method.getAnnotation(Loggable.class));
170 }
171
172 /**
173 * Catch exception and re-call the method.
174 * @param point Joint point
175 * @param method The method
176 * @param annotation The annotation
177 * @return The result of call
178 * @throws Throwable If something goes wrong inside
179 * @checkstyle ExecutableStatementCountCheck (100 lines)
180 */
181 private Object wrap(final ProceedingJoinPoint point, final Method method,
182 final Loggable annotation) throws Throwable {
183 if (Thread.interrupted()) {
184 throw new IllegalStateException(
185 String.format(
186 "thread '%s' in group '%s' interrupted",
187 Thread.currentThread().getName(),
188 Thread.currentThread().getThreadGroup().getName()
189 )
190 );
191 }
192 final long start = System.nanoTime();
193 final MethodLogger.Marker marker =
194 new MethodLogger.Marker(point, annotation);
195 this.running.add(marker);
196 int level = annotation.value();
197 try {
198 final Object logger = this.logger(method, annotation.name());
199 if (annotation.prepend()) {
200 LogHelper.log(
201 level,
202 logger,
203 new StringBuilder(
204 Mnemos.toText(
205 point,
206 annotation.trim(),
207 annotation.skipArgs(),
208 annotation.logThis()
209 )
210 ).append(": entered").toString()
211 );
212 }
213 final Object result = point.proceed();
214 final long nano = System.nanoTime() - start;
215 if (LogHelper.enabled(level, logger)
216 || this.over(annotation, nano)) {
217 if (this.over(annotation, nano)) {
218 level = Loggable.WARN;
219 }
220 LogHelper.log(
221 level, logger,
222 this.message(point, method, annotation, result, nano)
223 );
224 }
225 return result;
226 // @checkstyle IllegalCatch (1 line)
227 } catch (final Throwable ex) {
228 if (!MethodLogger.contains(annotation.ignore(), ex)
229 && !ex.getClass().isAnnotationPresent(Loggable.Quiet.class)) {
230 final StackTraceElement[] traces = ex.getStackTrace();
231 final String origin;
232 if (traces.length > 0) {
233 final StackTraceElement trace = traces[0];
234 origin = MethodLogger.oneText(trace);
235 } else {
236 origin = "somewhere";
237 }
238 LogHelper.log(
239 level,
240 method.getDeclaringClass(),
241 Logger.format(
242 "%s: thrown %s out of %s in %[nano]s",
243 Mnemos.toText(
244 point,
245 annotation.trim(),
246 annotation.skipArgs(),
247 annotation.logThis()
248 ),
249 Mnemos.toText(ex),
250 origin,
251 System.nanoTime() - start
252 )
253 );
254 }
255 throw ex;
256 } finally {
257 this.running.remove(marker);
258 }
259 }
260
261 /**
262 * Has time for method execution passed.
263 * @param annotation Loggable annotation.
264 * @param nano Execution time.
265 * @return Is over time limit.
266 */
267 private boolean over(final Loggable annotation, final long nano) {
268 return nano > annotation.unit().toNanos(annotation.limit());
269 }
270
271 /**
272 * Prepared message for log.
273 * @param point JointPoint to use.
274 * @param method Method for which to log.
275 * @param annotation Loggable annotation.
276 * @param result Method result.
277 * @param nano Method execution time.
278 * @return Log message.
279 * @checkstyle ParameterNumberCheck (3 lines)
280 */
281 private String message(final ProceedingJoinPoint point, final Method method,
282 final Loggable annotation, final Object result, final long nano) {
283 final StringBuilder msg = new StringBuilder();
284 msg.append(
285 Mnemos.toText(
286 point,
287 annotation.trim(),
288 annotation.skipArgs(),
289 annotation.logThis()
290 )
291 ).append(':');
292 if (!method.getReturnType().equals(Void.TYPE)) {
293 msg.append(' ').append(
294 Mnemos.toText(
295 result,
296 annotation.trim(),
297 annotation.skipResult()
298 )
299 );
300 }
301 msg.append(
302 Logger.format(
303 String.format(
304 " in %%[nano].%ds", annotation.precision()
305 ),
306 nano
307 )
308 );
309 if (this.over(annotation, nano)) {
310 msg.append(" (too slow!)");
311 }
312 return msg.toString();
313 }
314
315 /**
316 * Get the destination logger for this method.
317 * @param method The method
318 * @param name The Loggable annotation
319 * @return The logger that will be used
320 */
321 private Object logger(final Method method, final String name) {
322 final Object source;
323 if (name.isEmpty()) {
324 source = method.getDeclaringClass();
325 } else {
326 source = name;
327 }
328 return source;
329 }
330
331 /**
332 * Checks whether array of types contains given type.
333 * @param array Array of them
334 * @param exp The exception to find
335 * @return TRUE if it's there
336 */
337 private static boolean contains(final Class<? extends Throwable>[] array,
338 final Throwable exp) {
339 boolean contains = false;
340 for (final Class<? extends Throwable> type : array) {
341 if (MethodLogger.instanceOf(exp.getClass(), type)) {
342 contains = true;
343 break;
344 }
345 }
346 return contains;
347 }
348
349 /**
350 * The type is an instance of another type?
351 * @param child The child type
352 * @param parent Parent type
353 * @return TRUE if child is really a child of a parent
354 */
355 private static boolean instanceOf(final Class<?> child,
356 final Class<?> parent) {
357 boolean instance = child.equals(parent)
358 || (child.getSuperclass() != null
359 && MethodLogger.instanceOf(child.getSuperclass(), parent));
360 if (!instance) {
361 for (final Class<?> iface : child.getInterfaces()) {
362 instance = MethodLogger.instanceOf(iface, parent);
363 if (instance) {
364 break;
365 }
366 }
367 }
368 return instance;
369 }
370
371 /**
372 * Textualize a stacktrace.
373 * @param trace Array of stacktrace elements
374 * @return The text
375 */
376 private static String allText(final StackTraceElement... trace) {
377 final StringBuilder text = new StringBuilder();
378 for (int pos = 0; pos < trace.length; ++pos) {
379 if (text.length() > 0) {
380 text.append(", ");
381 }
382 text.append(MethodLogger.oneText(trace[pos]));
383 }
384 return text.toString();
385 }
386
387 /**
388 * Textualize a stacktrace.
389 * @param trace One stacktrace element
390 * @return The text
391 */
392 private static String oneText(final StackTraceElement trace) {
393 return String.format(
394 "%s#%s[%d]",
395 trace.getClassName(),
396 trace.getMethodName(),
397 trace.getLineNumber()
398 );
399 }
400
401 /**
402 * Marker of a running method.
403 */
404 private static final class Marker
405 implements Comparable<MethodLogger.Marker> {
406 /**
407 * When the method was started, in milliseconds.
408 */
409 private final transient long started;
410 /**
411 * Which monitoring cycle was logged recently.
412 */
413 private final transient AtomicInteger logged;
414 /**
415 * The thread it's running in.
416 */
417 @SuppressWarnings("PMD.DoNotUseThreads")
418 private final transient Thread thread;
419 /**
420 * Joint point.
421 */
422 private final transient ProceedingJoinPoint point;
423 /**
424 * Annotation.
425 */
426 private final transient Loggable annotation;
427 /**
428 * Public ctor.
429 * @param pnt Joint point
430 * @param annt Annotation
431 */
432 protected Marker(final ProceedingJoinPoint pnt, final Loggable annt) {
433 this.started = System.currentTimeMillis();
434 this.logged = new AtomicInteger();
435 this.point = pnt;
436 this.annotation = annt;
437 this.thread = Thread.currentThread();
438 }
439 /**
440 * Monitor it's status and log the problem, if any.
441 */
442 public void monitor() {
443 final TimeUnit unit = this.annotation.unit();
444 final long threshold = this.annotation.limit();
445 final long age = unit.convert(
446 System.currentTimeMillis() - this.started, TimeUnit.MILLISECONDS
447 );
448 final int cycle = (int) ((age - threshold) / threshold);
449 if (cycle > this.logged.get()) {
450 final Method method = MethodSignature.class.cast(
451 this.point.getSignature()
452 ).getMethod();
453 Logger.warn(
454 method.getDeclaringClass(),
455 "%s: takes more than %[ms]s, %[ms]s already, thread=%s/%s",
456 Mnemos.toText(this.point, true, this.annotation.skipArgs()),
457 TimeUnit.MILLISECONDS.convert(threshold, unit),
458 TimeUnit.MILLISECONDS.convert(age, unit),
459 this.thread.getName(),
460 this.thread.getState()
461 );
462 Logger.debug(
463 method.getDeclaringClass(),
464 "%s: thread %s/%s stacktrace: %s",
465 Mnemos.toText(this.point, true, this.annotation.skipArgs()),
466 this.thread.getName(),
467 this.thread.getState(),
468 MethodLogger.allText(this.thread.getStackTrace())
469 );
470 this.logged.set(cycle);
471 }
472 }
473 @Override
474 public int hashCode() {
475 return this.point.hashCode();
476 }
477 @Override
478 public boolean equals(final Object obj) {
479 return obj == this || MethodLogger.Marker.class.cast(obj)
480 .point.equals(this.point);
481 }
482 @Override
483 public int compareTo(final Marker marker) {
484 int cmp = 0;
485 if (this.started < marker.started) {
486 cmp = 1;
487 } else if (this.started > marker.started) {
488 cmp = -1;
489 }
490 return cmp;
491 }
492 }
493
494 }