Log 打印当前代码行数及类名
Posted AAA啊哈
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Log 打印当前代码行数及类名相关的知识,希望对你有一定的参考价值。
本文
http://afra55.github.io/2017/11/14/auto-get-current-code-line/
LogUtils
/**
* Created by Afra55 on 2017/11/14.
* Smile is the best name card.
*/
public class LogUtils
private static String getSimpleClassName(String name)
int lastIndex = name.lastIndexOf(".");
return name.substring(lastIndex + 1);
public static void i(String msg)
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
int methodCount = 1;
int stackOffset = getStackOffset(trace);
if (methodCount + stackOffset > trace.length)
methodCount = trace.length - stackOffset - 1;
for (int i = methodCount; i > 0; i--)
int stackIndex = i + stackOffset;
if (stackIndex >= trace.length)
continue;
StackTraceElement element = trace[stackIndex];
StringBuilder builder = new StringBuilder();
builder.append(getSimpleClassName(element.getClassName()))
.append(".")
.append(element.getMethodName())
.append(" ")
.append(" (")
.append(element.getFileName())
.append(":")
.append(element.getLineNumber())
.append(")")
.append(" | ")
.append(msg);
Log.i(getSimpleClassName(element.getClassName()), builder.toString());
private static int getStackOffset(StackTraceElement[] trace)
for (int i = 2; i < trace.length; i++)
StackTraceElement e = trace[i];
String name = e.getClassName();
if (!name.equals(LogUtils.class.getName()))
return --i;
return -1;
举例
public class MainActivity extends Activity
private void onJJ()
onBB();
private void onBB()
LogUtils.i("onBB");
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LogUtils.i("message");
onJJ();
输出日志:
I/MainActivity: MainActivity.onCreate (MainActivity.java:32) | message
I/MainActivity: MainActivity.onBB (MainActivity.java:25) | onBB
以上是关于Log 打印当前代码行数及类名的主要内容,如果未能解决你的问题,请参考以下文章
麒麟系统开发笔记:在国产麒麟系统上使用gdb定位崩溃异常方法流程进阶定位代码行数及专项测试Demo
UNIX命令,统计当前目录(含子目录)下所有后缀为.log的文件中ERROR出现的行数
Android 封装Log工具并上传Log文件到服务器(带类名方法名行数Crash的捕捉)