logging-with-aspectj

http://www.christianschenk.org/blog/logging-with-aspectj/

 

Logging with AspectJ

August 3rd, 2007 | Tech

Again, I would like to endorse the usage of aspect oriented programming because it may ease development significantly. That’s almost always the case with crosscutting concerns like logging and in this post we’ll develop a solution with AspectJ. So, adding logging to your application is as easy as this:

  • implement this AbstractLoggingAspect and define the methods you’d like to monitor
  • declare advice beforeafter or around the logging pointcut and println your logging to stdout.

Once you’re finished with this you’ve got logging in your application without touching the original code. We’ll have a look at the details in the next sections.

If you’d like to check out the code that accompanies this post you can download the Eclipse project as tar.gz or zip; make sure to install the AspectJ Development Tools. You can browse the code online here.

 

The logging template

The abstract aspect I wrote was inspired by the IndentedLogging aspect from the bookAspectJ in Action by Ramnivas Laddad. My AbstractLoggingAspect class does the following:

  • indents logging and
  • supplies an abstract method.

The abstract method needs to be implemented by an aspect, that defines things that should be monitored. The advice for this logging method should just print messages tostdout with System.out‘s println – this way they’re getting indented.

Implementing the aspect

A subclass of AbstractLoggingAspect implements the logging method and uses a pointcut to define join points that should be monitored. I wrote one for the sample code like so:

@Pointcut("(execution(* *.*doEverything()) ||
            execution(* *.*doSomething())) &&
           !within(*Test)")
protected void logging() {}

Every execution of the methods doEverything and doSomething that isn’t inside a test class will be matched. After that we can write an around advice to print some logging information. If you would run the sample code it would print the following:

Entering [MyLogic.doEverything()]
  Doing everything...
  Entering [A.doSomething()]
    Doing : A
  Leaving  [A.doSomething()]
  Entering [B.doSomething()]
    Doing : B
  Leaving  [B.doSomething()]
Leaving  [MyLogic.doEverything()]

The calls to the different methods are logged and indented.

Conclusion

Adding fancy indented logging to your application with AspectJ is very easy: subclass theAbstractLoggingAspect and customize the logging to your needs. After that you’ve logging in your application without changing the original code – all the work gets done inside the aspects.

你可能感兴趣的:(logging-with-aspectj)