Android开发:Log2File工具类

Log2File工具类是用于Android程序将Log记录到文件中(如sd卡)的工具,应用场景:



1. 无法连接电脑进行调试(usb线被usbotg占用)
2. Log不容易被抓取
3. Bug出现很随机,不是必出现
4. 其他自己脑补

## 0.说明

这篇文章最早是在我的CSDN博客上面发布了:http://blog.csdn.net/grackergao/article/details/18322749 .现在讲他转移到了这里,代码的Github地址 :https://github.com/Gracker/Android-Utils/blob/master/Log2File.java



## 1.Log2File工具类源码

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import android.content.Context;
import android.os.Environment;

public class Log2File
{
private static boolean logInit;
private static BufferedWriter writer;

private Log2File()
{

}

/
初始化Log,创建log文件 @param ctx
@param fileName @return
*/
public static boolean init(Context ctx, String fileName)
{
if(!logInit)
{
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state))
{
File sdDir = Environment.getExternalStorageDirectory();
File logDir = new File(sdDir.getAbsolutePath() + “/log2file/“ +
ctx.getPackageName() + “/“);

try {
if(!logDir.exists())
{
logDir.mkdirs();
}

File logFile = new File(logDir, fileName);
logFile.createNewFile();

writer = new BufferedWriter(new FileWriter(logFile, true));
logInit = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

return logInit;
}

/

写一条log @param msg
/
public static void w(String msg)
{
if(logInit)
{
try {
Date date = new Date();
writer.write(“[“ + date.toLocaleString() + “] “ + msg);
writer.newLine();
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}

/**
关闭log
*/
public static void close()
{
if(logInit)
{
try {
writer.close();
writer = null;

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

logInit = false;
}
}
}


## 2.Log2File类的使用

这个工具类的使用比较简单

1.首先调用init进行初始化


Log2File.init(context, fileName);

2.调用w()进行输出
Log2File.w(String msg);

3.使用完毕后,记得要关闭Log
Log2File.close();


文章目录
|