1.建一个写入文件的工具类
public class LogToFile {
private static String TAG = "LogToFile";
private static String logPath = null;//log日志存放路径
private static String fileName = null;
private static Date date = new Date();//因为log日志是使用日期命名的,使用静态成员变量主要是为了在整个程序运行期间只存在一个.log文件中;
/**
* 初始化,须在使用之前设置,最好在Application创建时调用
*
* @param context
*/
public static void init(Context context) {
logPath = getFilePath(context) + "/Logs";//获得文件储存路径,在后面加"/Logs"建立子文件夹
fileName = logPath + "/log_" + StringUtils.getDate() + ".txt";//log日志名,使用时间命名,保证不重复
File path = new File(logPath);
if (!path.exists()) {
path.mkdirs();
}
try {
File file = new File(fileName);
if (fileName.contains(StringUtils.getDate())) {
if (file.exists()) {
FileWriter fileWriter = new FileWriter(file, true);
fileWriter.write("");
fileWriter.flush();
fileWriter.close();
}
} else {
if (file.exists()) {
FileWriter fileWriter = new FileWriter(file);
fileWriter.write("");
fileWriter.flush();
fileWriter.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获得文件存储路径
*
* @return
*/
private static String getFilePath(Context context) {
if (Environment.MEDIA_MOUNTED.equals(Environment.MEDIA_MOUNTED) || !Environment.isExternalStorageRemovable()) {//如果外部储存可用
return context.getExternalFilesDir(null).getPath();//获得外部存储路径,默认路径为 /storage/emulated/0/Android/data/包名/files/Logs/log_日期
} else {
return context.getFilesDir().getPath();//直接存在/data/data里,非root手机是看不到的
}
}
private static final char VERBOSE = 'v';
private static final char DEBUG = 'd';
private static final char INFO = 'i';
private static final char WARN = 'w';
private static final char ERROR = 'e';
public static void v(String tag, String msg) {
writeToFile(VERBOSE, tag, msg);
}
public static void d(String tag, String msg) {
writeToFile(DEBUG, tag, msg);
}
public static void i(String tag, String msg) {
writeToFile(INFO, tag, msg);
}
public static void w(String tag, String msg) {
writeToFile(WARN, tag, msg);
}
public static void e(String tag, String msg) {
writeToFile(ERROR, tag, msg);
}
/**
* 将log信息写入文件中
*
* @param type
* @param tag
* @param msg
*/
private static void writeToFile(char type, String tag, String msg) {
if (null == logPath) {
return;
}
String log =StringUtils.getDate()+" "+msg+"\n";//log日志内容,可以自行定制
FileOutputStream fos = null;//FileOutputStream会自动调用底层的close()方法,不用关闭
BufferedWriter bw = null;
try {
fos = new FileOutputStream(fileName, true);//这里的第二个参数代表追加还是覆盖,true为追加,flase为覆盖
bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(log);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();//关闭缓冲流
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.//初始化log日志
LogToFile.init(getApplicationContext());
3. //调用保存log方法
LogToFile.d(TAG,i+"");
4.用到的工具类
public class StringUtils {
/**
* 返回当前日期
*/
public static String getDate() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
String str = formatter.format(curDate);
return str;
}
}
另外收集崩溃日志
//记录崩溃信息
final Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
//获取崩溃时的UNIX时间戳
long timeMillis = System.currentTimeMillis();
//将时间戳转换成人类能看懂的格式,建立一个String拼接器
StringBuilder stringBuilder = new StringBuilder(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date(timeMillis)));
stringBuilder.append(":\n");
//获取错误信息
stringBuilder.append(throwable.getMessage());
stringBuilder.append("\n");
//获取堆栈信息
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
throwable.printStackTrace(pw);
stringBuilder.append(sw.toString());
//这就是完整的错误信息了,你可以拿来上传服务器,或者做成本地文件保存等等等等
String errorLog = stringBuilder.toString();
String s = toUtf8(errorLog);
LogToFile.d("TAG", s);
//最后如何处理这个崩溃,这里使用默认的处理方式让APP停止运行
defaultHandler.uncaughtException(thread, throwable);
}
});