Android输出日志Log类并保存到文件中

android.util.Log常用的方法有以下5个: 

Log.v() Log.d() Log.i() Log.w() 以及 Log.e()。根据首字母分别对应VERBOSE,DEBUG,INFO,WARN,ERROR。 

1、Log.v 的调试颜色为黑色的,任何消息都会输出,这里的v代表verbose啰嗦的意思,平时使用就是Log.v("",""); 

2、Log.d的输出颜色是蓝色的,仅输出debug调试的意思,但他会输出上层的信息,过滤起来可以通过DDMS的Logcat标签来选择。

3、Log.i的输出为绿色,一般提示性的消息information,它不会输出Log.v和Log.d的信息,但会显示i、w和e的信息。

4、Log.w的意思为橙色,可以看作为warning警告,一般需要我们注意优化Android代码,同时选择它后还会输出Log.e的信息。 

5、Log.e为红色,可以想到error错误,这里仅显示红色的错误信息,这些错误就需要我们认真的分析,查看栈的信息了。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

public class MyLog {

     

    private static Boolean MYLOG_SWITCH = true// 日志文件总开关

    private static Boolean MYLOG_WRITE_TO_FILE = true;// 日志写入文件开关

    private static char MYLOG_TYPE = 'v';// 输入日志类型,w代表只输出告警信息等,v代表输出所有信息

    private static String MYLOG_PATH_SDCARD_DIR = "/sdcard/kantu/log";// 日志文件在sdcard中的路径

    private static int SDCARD_LOG_FILE_SAVE_DAYS = 0;// sd卡中日志文件的最多保存天数

    private static String MYLOGFILEName = "Log.txt";// 本类输出的日志文件名称

    private static SimpleDateFormat myLogSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 日志的输出格式

    private static SimpleDateFormat logfile = new SimpleDateFormat("yyyy-MM-dd");// 日志文件格式

    public Context context;

 

    public static void w(String tag, Object msg) { // 警告信息

        log(tag, msg.toString(), 'w');

    }

 

    public static void e(String tag, Object msg) { // 错误信息

        log(tag, msg.toString(), 'e');

    }

 

    public static void d(String tag, Object msg) {// 调试信息

        log(tag, msg.toString(), 'd');

    }

 

    public static void i(String tag, Object msg) {//

        log(tag, msg.toString(), 'i');

    }

 

    public static void v(String tag, Object msg) {

        log(tag, msg.toString(), 'v');

    }

 

    public static void w(String tag, String text) {

        log(tag, text, 'w');

    }

 

    public static void e(String tag, String text) {

        log(tag, text, 'e');

    }

 

    public static void d(String tag, String text) {

        log(tag, text, 'd');

    }

 

    public static void i(String tag, String text) {

        log(tag, text, 'i');

    }

 

    public static void v(String tag, String text) {

        log(tag, text, 'v');

    }

 

    /**

     * 根据tag, msg和等级,输出日志

     * @param tag

     * @param msg

     * @param level

     */

    private static void log(String tag, String msg, char level) {

        if (MYLOG_SWITCH) {//日志文件总开关

            if ('e' == level && ('e' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { // 输出错误信息

                Log.e(tag, msg);

            else if ('w' == level && ('w' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) {

                Log.w(tag, msg);

            else if ('d' == level && ('d' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) {

                Log.d(tag, msg);

            else if ('i' == level && ('d' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) {

                Log.i(tag, msg);

            else {

                Log.v(tag, msg);

            }

            if (MYLOG_WRITE_TO_FILE)//日志写入文件开关

                writeLogtoFile(String.valueOf(level), tag, msg);

        }

    }

 

    /**

     * 打开日志文件并写入日志

     * @param mylogtype

     * @param tag

     * @param text

     */

    private static void writeLogtoFile(String mylogtype, String tag, String text) {// 新建或打开日志文件

        Date nowtime = new Date();

        String needWriteFiel = logfile.format(nowtime);

        String needWriteMessage = myLogSdf.format(nowtime) + "    " + mylogtype + "    " + tag + "    " + text;

        File dirPath = Environment.getExternalStorageDirectory();

 

        File dirsFile = new File(MYLOG_PATH_SDCARD_DIR);

        if (!dirsFile.exists()){

            dirsFile.mkdirs();

        }

        //Log.i("创建文件","创建文件");

        File file = new File(dirsFile.toString(), needWriteFiel + MYLOGFILEName);// MYLOG_PATH_SDCARD_DIR

        if (!file.exists()) {

            try {

                //在指定的文件夹中创建文件

                file.createNewFile();

            catch (Exception e) {

            }

        }

 

        try {

            FileWriter filerWriter = new FileWriter(file, true);// 后面这个参数代表是不是要接上文件中原来的数据,不进行覆盖

            BufferedWriter bufWriter = new BufferedWriter(filerWriter);

            bufWriter.write(needWriteMessage);

            bufWriter.newLine();

            bufWriter.close();

            filerWriter.close();

        catch (IOException e) {

            e.printStackTrace();

        }

    }

 

    /**

     * 删除制定的日志文件

     */

    public static void delFile() {// 删除日志文件

        String needDelFiel = logfile.format(getDateBefore());

        File dirPath = Environment.getExternalStorageDirectory();

        File file = new File(dirPath, needDelFiel + MYLOGFILEName);// MYLOG_PATH_SDCARD_DIR

        if (file.exists()) {

            file.delete();

        }

    }

 

    /**

     * 得到现在时间前的几天日期,用来得到需要删除的日志文件名

     */

    private static Date getDateBefore() {

        Date nowtime = new Date();

        Calendar now = Calendar.getInstance();

        now.setTime(nowtime);

        now.set(Calendar.DATE, now.get(Calendar.DATE) - SDCARD_LOG_FILE_SAVE_DAYS);

        return now.getTime();

    }

}

  注:还需要在AndroidManifest.xml文件中添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

参考于:https://www.cnblogs.com/jeffen/p/6828569.html

 

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Android ,我们可以使用日志框架 Logcat 来输出日志信息,但是 Logcat 的输出信息只能在控制台查看,无法保存文件。如果需要将日志信息保存文件,可以通过以下步骤实现按天为单位保存: 1. 创建保存日志信息的目录 在 Android ,我们可以使用 `Context.getFilesDir()` 方法获取应用程序的私有目录,然后在这个目录下创建一个名为“log”的目录,用于保存日志信息。 ```java File logDir = new File(getFilesDir(), "log"); if (!logDir.exists()) { logDir.mkdir(); } ``` 2. 定义日志文件名称 在保存日志信息时,需要为每个日志文件定义一个唯一的名称,可以根据当前日期来生成日志文件名称。可以使用 `SimpleDateFormat` 来格式化日期。 ```java SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); String logFileName = dateFormat.format(new Date()) + ".log"; ``` 3. 将日志信息写入文件输出日志信息时,可以将日志信息写入到指定的日志文件。可以使用 `PrintWriter` 来实现写入文件操作。 ```java File logFile = new File(logDir, logFileName); PrintWriter writer = new PrintWriter(new FileWriter(logFile, true)); writer.println("[" + dateFormat.format(new Date()) + "] " + message); writer.flush(); writer.close(); ``` 完整的代码如下: ```java public static void log(String message) { try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); String logFileName = dateFormat.format(new Date()) + ".log"; File logDir = new File(getFilesDir(), "log"); if (!logDir.exists()) { logDir.mkdir(); } File logFile = new File(logDir, logFileName); PrintWriter writer = new PrintWriter(new FileWriter(logFile, true)); writer.println("[" + dateFormat.format(new Date()) + "] " + message); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } ``` 在应用程序调用 `log()` 方法输出日志信息时,将会按天为单位保存到指定的日志文件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值