Benjamin
Benjamin

Reputation: 10393

How to add names of class and function automatically to my log

I'm using android.util.Log

class Foo
{
  private void boo()
  {
    // This is the basic log of android.
    Log.i("tag", "Start");
  }
}

I want the log should be printed [Foo::boo] Start.
Can I get the class and function name in Java? Then how do I wrap the code?

Upvotes: 4

Views: 4506

Answers (3)

Mayank
Mayank

Reputation: 8852

here UPDATED

String tag = "[";
tag += this.getClass().toString();
tag += " :: ";
tag += Thread.currentThread().getStackTrace()[1].getMethodName().toString();
tag += "]";
Log.i(tag, "Message");

this.getClass().toString() will return class name as String

UPDATE

if function is static then use following code

String tag = "[";
tag += Thread.currentThread().getStackTrace()[1].getClassName().toString();
tag += " :: ";
tag += Thread.currentThread().getStackTrace()[1].getMethodName().toString();
tag += "]";
Log.i(tag, "Message");

Upvotes: 5

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132982

Get The Current Class Name and Function Name :

Log.i(getFunctionName(), "Start");

private String getFunctionName()    
    {    
        StackTraceElement[] sts = Thread.currentThread().getStackTrace();    
        if(sts == null)    
        {    
            return null;    
        }    
        for(StackTraceElement st : sts)    
        {    
            if(st.isNativeMethod())    
            {    
                continue;    
            }    
            if(st.getClassName().equals(Thread.class.getName()))    
            {    
                continue;    
            }    
            if(st.getClassName().equals(this.getClass().getName()))    
            {    
                continue;    
            }    
            return mClassName + "[ " + Thread.currentThread().getName() + ": "    
                    +  " "   + st.getMethodName() + " ]";    
        }    
        return null;    
    }    

Upvotes: 2

Chandra Sekhar
Chandra Sekhar

Reputation: 19502

You can use these methods of java.lang.Class class

getClass().getname() - to get the name of the class
getClass().getMethods() - to get the methods declared in that class.

Upvotes: 1

Related Questions