Java log all method calls

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

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 cannot import anything outside of Java 1.5 libraries. Is there some thing like what is available in Python?

Maybe if you told us your scenario(even if its slightly obfuscated) and what you are trying to accomplish this question could be a little more productive.

@nsfyn55 my accomplish this time is to create a «debug» version to put in production and see the real behavior of your code, some things strange and random is happen, and i like to see all steps (Ps.: Performance is not a issue now, even in production.)

6 Answers 6

Good tracing tool for Java is BTrace.

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

Yep, this is probably the way to go. Unfortunately it looks like waldecir is going to be stuck manually modifying bytecode since he/she can’t import a library like ASM or Javassist. Oh well.

That’s what that tutorial is for, «This article will show how to implement such a Java agent, which transparently will add entry and exit logging to all methods in all your classes with the standard Java Logging API.» Here’s the link again: today.java.net/pub/a/today/2008/04/24/…

Читайте также:  Абсолютный адрес

@Mike Daniels: we don’t know if the requirements of «not importing anything» are compile-time or runtime. One could easily use Javassist to postprocess a compiled code in such way that it has no dependencies. So the proposition to use Javassist seems quite good.

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.

Yeah ython dont do this, i need a way to add a decorator behaviour in all methods of a class to extract some informations.

Источник

Android: how to log all Activity methods calls?

I would like to have a quick way to be able to log all the calls to all the super methods called by the activity. I have tried this https://github.com/stephanenicolas/loglifecycle but for some reason it does not work with AppCompatActivity . I could ask my IDE to override all the methods; but how to add Log to all of them? Manually? There must be a way..

with Hugo you have to put @logsomethig in front of each method you want to log, same as doing manually :-(((

Unfortunately, I think you are going to have to bite the bullet and add them all manually. You could create a class to extend from that only has logging in it. That way you do not clutter your actual class, and you can reuse it in your other classes.

3 Answers 3

You could go around and play yourself with stacktrace

StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); 

The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.

EDIT: There seems to be a whole post about this HERE

stacktrace goes beyond activity only methods, it logs everything. You need to filter out the results if you want only activity methods, see the link I posted, it is very detailed.

you just need to setup aspect execution

about expressions you could read on AOP

No, it is big framework Aspect Oriented Programing. it has few stages pre-compile and run-time. So generally it is EE framework. but it is works perfect on android. So it is big tool for just logging porpoises. But TC task is regular issue for AOP.

EDITED: If you can afford going only API 14+ you can use

public void registerActivityLifecycleCallbacks (Application.ActivityLifecycleCallbacks callback) 

It doesn’t provide all methods, but have the most used ones.

abstract void onActivityCreated(Activity activity, Bundle savedInstanceState) abstract void onActivityDestroyed(Activity activity) abstract void onActivityPaused(Activity activity) abstract void onActivityResumed(Activity activity) abstract void onActivitySaveInstanceState(Activity activity, Bundle outState) abstract void onActivityStarted(Activity activity) abstract void onActivityStopped(Activity activity) 

Источник

How do I trace methods calls in Java?

After the program run, how do I trace (1) which object call which method (2) and how many times? Just a little precision, I might have 100 classes and 1000s of objects each of them calling 100s of methods. I want to be able to trace (after I run the program), which object called which method and how many times. Thanks for any suggestion.

Are you asking about more complex or general examples? From this example, it would be obvious, since you only have one instance of each class and there is no inheritance.

@DanielNugent I am looking for an answer for use in any situation. I might have 100 classes and 1000s of objects calling each 100s of methods. I want to be able to trace (after I run the program), which object called which method and how many times. Thanks — George

2 Answers 2

This prints a line for each method call of all objects in all threads:

Runtime.traceMethodCalls() (deprecated / no-op in Java 9)
Runtime.traceInstructions (deprecated / no-op in Java 9)

You can use a call tracer like housemd or btrace or inTrace

For more involved analysis, you can use a call graph utility like one of these:

(here is an article on the subject)

The deprecated methods above are slated for removal, because there are now JVM-specific alternatives:

  • Java Flight Recorder Part of JDK 7 as of build 56. Requires commercial license for use in production
  • VisualVM Free/popular 3rd party

Both of those tools pretty easy to setup and start collecting information and have nice GUI interfaces. They attach to a running JVM process and allow for thread snapshots and various other kinds of diagnosis (Visual VM has a lot of available plugins but that can take awhile to sort through to configure and understand, if you want to go beyond default behavior, whereas JFR is instrumented with more by default).

Also, don’t underestimate the usefulness of JVM distributed command line utilities ( $JAVA_HOME/bin ), for performing some easily accessible diagnostics.

Источник

Log method entries with Spring AOP [duplicate]

Anyone has any idea on how to log method entries(including parameters value) and exit with Spring AOP and log4j at trace level. It should be able to log classes from multiple packages.

2 Answers 2

You can use @Around(..) aspect for such purposes:

@Component @Aspect @Order(value=2) public class LoggingAspect < @Around("execution(* com.blablabla.server..*.*(..))") public Object logMethod(ProceedingJoinPoint joinPoint) throws Throwable< final Logger logger = LoggerFactory.getLogger(joinPoint.getTarget().getClass().getName()); Object retVal = null; try < StringBuffer startMessageStringBuffer = new StringBuffer(); startMessageStringBuffer.append("Start method "); startMessageStringBuffer.append(joinPoint.getSignature().getName()); startMessageStringBuffer.append("("); Object[] args = joinPoint.getArgs(); for (int i = 0; i < args.length; i++) < startMessageStringBuffer.append(args[i]).append(","); >if (args.length > 0) < startMessageStringBuffer.deleteCharAt(startMessageStringBuffer.length() - 1); >startMessageStringBuffer.append(")"); logger.trace(startMessageStringBuffer.toString()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); retVal = joinPoint.proceed(); stopWatch.stop(); StringBuffer endMessageStringBuffer = new StringBuffer(); endMessageStringBuffer.append("Finish method "); endMessageStringBuffer.append(joinPoint.getSignature().getName()); endMessageStringBuffer.append("(..); execution time: "); endMessageStringBuffer.append(stopWatch.getTotalTimeMillis()); endMessageStringBuffer.append(" ms;"); logger.trace(endMessageStringBuffer.toString()); > catch (Throwable ex) < StringBuffer errorMessageStringBuffer = new StringBuffer(); // Create error message with exception logger.error(errorMessageStringBuffer.toString(), ex); throw ex; >return retVal; > > 

In this example around aspect logs all method calls for all subpackages under com.blablabla.server package. Also it logs all method input parameters.

You can use PerformanceMonitorInterceptor of Spring framework to log method entries.Here is the sample usage from DZone.

Источник

How can i log every method called in a class automatically with log4j

I have a class with database calls, and I generally want to log every method called (with arguments) in this class with log4j:

logger.debug("foo(id="+id+") initiated"); 

Is it possible to do this automatically? Maybe by using some sort of annotation in start of each method instead of writing every single logger.debug? Today I have to update my logging.debug every time I change arguments or method name.

3 Answers 3

Try @Loggable annotation and an AspectJ aspect from jcabi-aspects (I’m a developer):

@Loggable(Loggable.INFO) public String load(URL url)

All method calls are logged through SLF4J.

This blog post explains it step by step: Java Method Logging with AOP and Annotations

Hi, can you please add a full working example of how to set up jcabi-aspects , including the pom.xml ? A URL to a tutorial webpage would be fine. Thanks!

You can see a real project, where it all works just fine: github.com/yegor256/jare I also added the link to the blog post

If you have interfaces declaring the methods you want to log calls to, you can use the standard Proxy API to achieve what you want.

The Proxy API would allow you to wrap your actual implementation in a new, proxy class, that would log the call, and the forward the call to implementation. You just have to implement one InvocationHandler that does the logging and the forwarding.

interface Calculator < int add(int a, int b); >class CalculatorImpl implements Calculator < @Override public int add(int a, int b) < return a+b; >> class LoggingInvocationHandler implements InvocationHandler < private final Object delegate; public LoggingInvocationHandler(final Object delegate) < this.delegate = delegate; >@Override invoke(Object proxy, Method method, Object[] args) throws Throwable < System.out.println("method: " + method + ", args: " + args); return method.invoke(delegate, args); >> class X < public static void main(String. args) < final Calculator calc = new CalculatorImpl(); final Calculator loggingCalc = (Calculator) Proxy.newProxyInstance(X.class.getClassLoader(), new Class[] , new LoggingInvocationHandler (calc)); loggingCalc.add(2, 3); // shall print to the screen > > 

You can also easily log the return values and exceptions thrown by the methods, just by changing the code in the InvocationHandler . Also, you could use any logging framework you like instead of System.out.println as in the example.

To log return values and exceptions, you could do something like:

 @Override invoke(Object proxy, Method method, Object[] args) throws Throwable < System.out.println("method: " + method + ", args: " + args); try < final Object ret = method.invoke(delegate, args); System.out.println("return: " + ret); return ret; >catch (Throwable t) < System.out.println("thrown: " + t); throw t; >> 

Источник

Оцените статью