Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating our own aspects using custom annotations

I am new to Annotations and new to StackOverflow and this is my first question. I am trying to write custom annotations which will help me trace and log method executions.

For example:

class A
{

@Logthis

void methodA();

}

Here whenever the method methodA() is executed, I want to log to a file telling "we are entering the methodA in class A" and when methodA is over "we are exiting methodA in class A" something like this. We vil have a number of classes and methods.

I know that this can be done using AspectJ. I have done it by defining pointcuts and joinpoints. But I want to do it using custom annotations.

It will be very helpful if anyone can guide me as to how to go about this.

Thanks in advance.

like image 707
yash6 Avatar asked Aug 31 '25 04:08

yash6


2 Answers

Using AspectJ you do the following :-

Create an Aspect Class annotated with @Aspect

Annotation a method in the class with @Around and define the value to be execution on classes that you have annotated. You will also need to have enabled proxying of you classes by AspectJ.

@Aspect
public class LoggerAspect {

    @Around(value = "execution(@you.custom.Annotation * *(..))")
    public Object logMethod(ProceedingJoinPoint joinPoint) throws Throwable
    {
        // DO LOGGING HERE
    }

}
like image 198
bstick12 Avatar answered Sep 03 '25 02:09

bstick12


You can use Log4J. Here is a tutorial of it:

http://javakane.blogspot.fr/2012/07/automate-log4j-logging-with-aop-and.html

like image 37
tchike Avatar answered Sep 03 '25 02:09

tchike