开发者

How to log/trace any method call of object in java

开发者 https://www.devze.com 2023-04-01 09:41 出处:网络
I need some thing like a Python decorator. I need to store some information, specifically the method called, its start time, its end time, and its arguments. I开发者_JS百科 cannot import anything outs

I need some thing like a Python decorator. I need to store some information, specifically the method called, its start time, its end time, and its arguments. I开发者_JS百科 cannot import anything outside of Java 1.5 libraries. Is there some thing like what is available in Python?


Good tracing tool for Java is BTrace.


You can try some profiler using Java Management Extensions or java agent.

See http://java.sun.com/developer/technicalArticles/releases/j2se15/#mnm


Java Instrumentation?

http://download.oracle.com/javase/6/docs/api/java/lang/instrument/Instrumentation.html

Example:

http://today.java.net/pub/a/today/2008/04/24/add-logging-at-class-load-time-with-instrumentation.html


No, Python decorators do not let you monitor all the code without changing anything. You still have to put your decorator everywhere (and - essentially - wrap each of your functions into a function that does the counting).

I am not sure if I understand your requirements (you do not say if you need the code for production or testing; also, the requirement "not to import anything" is bizarre: are all your classes in the default package? are you allowed to use an IDE and a compiler?), but I think the simplest way would be to use Javassist (the second link kindly provided by cschooley is a perfect introduction), but do not use the agent: instead use CtClass#write() to instrument class files and save them to disk (possibly in a custom ant task). This way the final build will not need any special set-up.


You might get away with a Java Proxy class if you can rely on interface methods only.


@Loggable annotation and an AspectJ aspect from jcabi-aspects may help you. Annotate all your methods and every time they are being called SLF4J will receive log messages:

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

In the next versions of jcabi-aspects a full logging of a class will be implemented: https://github.com/yegor256/jcabi/issues/129

0

精彩评论

暂无评论...
验证码 换一张
取 消