Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 979
Benjamin Avatar asked Feb 22 '23 00:02

Benjamin


2 Answers

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");
like image 106
Mayank Avatar answered Feb 23 '23 13:02

Mayank


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;    
    }    
like image 20
ρяσѕρєя K Avatar answered Feb 23 '23 12:02

ρяσѕρєя K