Is there any way to automatically log the method name in Android?

Viewed 17054

I'm using this kind of pattern:

public class FooProvider extends ContentProvider {
    private static final String TAG = FooProvider.class.getSimpleName(); 
    ...

    @Override
    public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
        l.v(TAG, TAG + ".update() Uri:" + uri.toString() + " " + db.getPath());

Where l is my wrapper round Androids Log.v which takes String... args. This gives logcat output like this:

FooProvider.update() Uri: foo bar etc

What I'm looking for is a way to log the method name, in this case update(), automatically and in a way which survives refactoring the way TAG does. I've seen the class.getMethods() call but can't see a way to index the returned list with the current method at runtime.

6 Answers

You only need addition message and input to this function to auto create log

private static String buildMsg(String msg) {
    StringBuilder buffer = new StringBuilder();

    if (DETAIL_ENABLE) {
        final StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[4];
        buffer.append("[ ");
        buffer.append(Thread.currentThread().getName());
        buffer.append(": ");
        buffer.append(stackTraceElement.getFileName());
        buffer.append(": ");
        buffer.append(stackTraceElement.getLineNumber());
        buffer.append(": ");
        buffer.append(stackTraceElement.getMethodName());
    }

    buffer.append("() ] _____ ");

    buffer.append(msg);

    return buffer.toString();
}
Related