Wednesday 24 June 2015

AspectJ Example with log4j2


Develop an web application using AspectJ and log4j2.
1.       First we have to add required jars in WEB-INF/lib folder. The following jars are need to develop AspectJ with web application.


2.       Secondly we will create META-INF folder under src folder.

3.       Next we will add aop.xml file under META-INF folder like below structure.
4.       My requirement is I want to log each and every public method entrance and exit inside my project.
5.       For this we need to create one aspect class and one configuration file (aop.xml).
6.       AspectJ provides some annotations like @Before, @After, @AfterReturning, @AfterThrowing ,@Around, @Pointcut
7.       Now we are using @Before and @After. Here @Before defines before each and every public method calling and @After defines each and every public method after calling.
8.       Create a class for aspect  .Here I am creating LogAspect.java

LogAspect.java

@Aspect
public class LogAspect {
       private static Logger logger = LogManager.getLogger(LogAspect.class);
       @Pointcut("execution(public * *.*(..))")
       public void defineEntryPoint() {
       }

       @Before("defineEntryPoint()")
       public void beforeMethod(JoinPoint joinPoint) {
//            System.out.println("Before" + joinPoint.getSignature());
              logger.info("Before : " + joinPoint.getSignature());
       }

       @After("defineEntryPoint()")
       public void afterMethod(JoinPoint joinPoint) {
//            System.out.println("After" + joinPoint.getSignature());
       logger.info("After :" + joinPoint.getSignature());
       }
}

9.       Now add aop.xml file. In this file we configure LogAspect class and what are all the packages weave the AspectJ agent.
           aop.xml
<!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>
       <weaver>
              <!-- only weave classes in our application-specific packages -->

              <include within="com.msr..*" />
       </weaver>
       <aspects>
              <!-- weave in just this aspect -->
              <aspect name="com.msr.aspects.LogAspect" />
       </aspects>
</aspectj>
10.   For testing purpose I am creating one servlet class.

Test.java

@WebServlet("/Test")
public class Test extends HttpServlet {
       private static final long serialVersionUID = 1L;

       public Test() {
              super();
              // TODO Auto-generated constructor stub
       }

       protected void doGet(HttpServletRequest request,
                     HttpServletResponse response) throws ServletException, IOException {
              PrintWriter out = null;
              try {
                     out = response.getWriter();
                    Sample.mySample();
                     out.write("hello from MyServlet");
              } catch (IOException e) {

                     e.printStackTrace();
              } finally {
                     if (out != null)
                           out.close();
              }
       }

}


Sample.java

public class Sample {
 public static void mySample(){
        System.out.println("this is my sample method");
 }
}

11.  For logs where we have store which pattern we have to store logs we have to configure in log4j2.xml file
               Log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" complete="true">
       <Appenders>
       <Console name="Console" target="SYSTEM_OUT">
              <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36}  -%l                                                                                                                                                        %msg%n -%X{userName}%n" />
              </Console>
       </Appenders>
       <Loggers>
              <Root level="all" additivity="false">
                     <AppenderRef ref="Console" />
              </Root>
       </Loggers>
</Configuration>

12.   Its important point now we have to configure aspetjweaver agent. Aspectj given agent for this i.e apectjweaver-1.8.5.jar in your class path and vm argument .
13.   If you are using eclipse for your application development follow below steps.
Right click on your project -> Run as -> Run configurations ->Arguments tab -> vm arguments  inside this pass path your aspectjweaver-1.8.5.jar.
e.g : -javaagent:D:\log4jproject\aspectjweaver-1.8.5.jar.




final structure like below.


14.   Run the web application and test using below url .


The output comes like below.
16:53:02.378 [http-bio-1111-exec-3] INFO  com.msr.aspects.LogAspect-com.msr.aspects.LogAspect.beforeMethod(LogAspect.java:25) – Before : void com.msr.aspects.Sample.mySample()
-
this is my sample method

16:53:02.381 [http-bio-1111-exec-3] INFO  com.msr.aspects.LogAspect-com.msr.aspects.LogAspect.afterMethod(LogAspect.java:31) – After : void com.msr.aspects.Sample.mySample()
 -






No comments:

Post a Comment