简体   繁体   中英

Java code instrumentation using annotations

I've got a huge java project with tons of code. Let us assume it looks like:

fn1(int arg1){...}
fn2(int arg1,int arg2){...}
fn23(){...}
...
fn134(){...}

I want to log each invocation of functions using annotations:

@logme("arg1")
fn1(int arg1){...}
@logme("all args")
fn2(int arg1,int arg2){...}
fn23(){...}
...
fn134(){...}

and expect seeing

fn1(arg1=223)
fn1(arg1=213,arg2=46)

in my log files

Would you be so kind to propose me some tool?

Steve

I would recommend to use AspectJ for this purpose. Here you can find a short documentation how to define the appropriate PointCuts

You may use AspectJ & any logging framework to handle this requirement, so you need to do the following:

1- create your annotation which take arguments as you may wish, or even take a string of undefined number of arguments, and process them like 'arg1=q,arg2=w,arg3=e'

2- create an aspect with point cut on your new annotation like this

@Pointcut(value = "@annotation(loggableActivity)", argNames = "loggableActivity")

notice that argNames used here to send the annotation itself to the handler method, so you can get arguments from it like 'arg1=q,arg2=w,arg3=e' , and process them

3- before proceeding the method call, log what ever you want about it, you can get almost all needed info from your arguments,

Annotation code looks like:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LoggableActivity {
    String value();

    String args() default "";
}

point cut code looks like:

@Aspect
public class ActivityLogger {

    private static final Logger logger = LoggerFactory.getLogger("activity");

    @Pointcut(value = "@annotation(loggableActivity)", argNames = "loggableActivity")
    public void loggableUserActivity(LoggableActivity loggableActivity) {

    }

    @Around("loggableUserActivity(loggableActivity)")
    public Object doLoggingUserActivity(ProceedingJoinPoint pjp,
            LoggableActivity loggableActivity) throws Throwable {}

then inside doLoggingUserActivity you may use methods like

pjp.proceed(); proceed method call
pjp.getArgs(); gets method arguments
loggableActivity.args(); gets annotation argument as String

then use logger to log them

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM