this library https://github.com/JakeWharton/hugo
is doing exactly what u want.
It is for android but if you not building for that it can be changed easily for your needs.
To remove android dependencies just replace those includes:
import android.os.Build;
import android.os.Looper;
import android.os.Trace;
import android.util.Log;
and where
android.util.Log
is used just put your logs instead.
here is a fast test for java only with an example
It uses aspectj https://eclipse.org/aspectj/
to place logs on specific points.
the use of aspects is quite neat and clean for example:
@Aspect
public class Hugo {
@Pointcut("execution(@hugo.weaving.DebugLog * *(..))")
public void method() {}
@Pointcut("execution(@hugo.weaving.DebugLog *.new(..))")
public void constructor() {}
Defines pointcuts where logs will be injected. In this example it looks for methods and constructors with annotation @hugo.weaving.DebugLog
Then
@Around("method() || constructor()")
public Object logAndExecute(ProceedingJoinPoint joinPoint) throws Throwable {
enterMethod(joinPoint);
long startNanos = System.nanoTime();
Object result = joinPoint.proceed();
long stopNanos = System.nanoTime();
long lengthMillis = TimeUnit.NANOSECONDS.toMillis(stopNanos - startNanos);
exitMethod(joinPoint, result, lengthMillis);
return result;
}
Defines how we want to log stuff and what to log. In 'enterMethod' we log method signature in 'exitMethod' we can log the result and the time spent in this method.
It is pretty simple and clean and at the same time quite powerful as is AspectJ intention.