Is it possible to log a method call in java (log4j

2019-02-26 16:58发布

问题:

Is it possible to log any method call in log4j Java?

Thanks!

回答1:

No, not without editing either the call-sites or the method itself. I think what you're after is something towards aspect oriented programming. Have a look at AspectJ for example.



回答2:

You can use %I in your Log4j conversion pattern to print out the name of the method. BUT be warned that "generating caller location information is extremely slow and should be avoided unless execution speed is not an issue."



回答3:

You can do it with AOP and Java annotations. I would recommend to use @Loggable annotation and an AspectJ aspect from jcabi-aspects (I'm a developer):

@Loggable(Loggable.DEBUG)
public String load(URL url) {
  return url.openConnection().getContent();
}

In SLF4J log output you will see method execution time, its parameters, and its name.