/**
* @author zuo
* @date 2018/6/20 12:37
*/
public class LogUtil {
private static final String FILE_NAME = "/logs.txt";
private static Boolean MYLOG_SWITCH = true; // 日志文件总开关
public static void i(String str) {
if (MYLOG_SWITCH) {
writeException(str);
}
}
public static void LogException(Exception e) {
if (MYLOG_SWITCH) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String str = sw.toString();
writeException(str);
} else {
e.printStackTrace();
}
}
private static void writeException(String content) {
try {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// 获取SD卡的目录
File sdCardDir = Environment.getExternalStorageDirectory();
File targetFile = new File(sdCardDir.getCanonicalPath()
+ FILE_NAME);
@SuppressLint("SimpleDateFormat")
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date());
String logStr = String.format("\n\n%s\n%s", date, content);
// 以指定文件创建RandomAccessFile对象
RandomAccessFile raf = new RandomAccessFile(targetFile, "rw");
// 将文件记录指针移动到最后
raf.seek(targetFile.length());
// 输出文件内容
raf.write(logStr.getBytes());
raf.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String readException() {
try {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// 获得SD卡对应的存储目录
File sdCardDir = Environment.getExternalStorageDirectory();
// 获取指定文件对应的输入流
FileInputStream fis = new FileInputStream(
sdCardDir.getCanonicalPath() + FILE_NAME);
// 将指定输入流包装成BufferReader
BufferedReader br = new BufferedReader(new InputStreamReader(
fis));
StringBuilder sb = new StringBuilder("");
String line = null;
// 循环读取文件内容
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
异常处理 - 生成问题记录日志
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 引言 看到一篇blog,感觉写的角度非常好,因此引用过来消化一番。 原文地址:http://blog.csdn.n...
- 1. ASP.NET Core 异常处理与日志记录[#1-aspnet-core-%E5%BC%82%E5%B8%...
- 在项目发展初期,可能由于数据量和用户访问量的原因,系统不会出现性能问题,但是随着项目发展,数据量发生具体变化,系统...
- 一、迭代器和生成器 可迭代对象:可以直接作用于for循环的对象统称为可迭代对象(iterable)用isinsta...