Android output Log class and save to file

There are five common methods for android.util.Log:

Log.v(), Log.d(), Log.i(), Log.w(), and Log.e(). Corresponding to VERBOSE,DEBUG,INFO,WARN,ERROR according to the initial.  

1. The debug color of Log.v is black, and any message will be output. V here represents verbose meaning, which is usually used as Log.v("", "");

2. The output color of Log.d is blue. It only outputs the meaning of debug debugging, but it will output the information of the upper layer. It can be selected through the Logcat tag of DDMS.

3. The output of Log.i is green. Generally, it will not output the information of Log.v and Log.d, but it will display the information of i, w and e.

4. Log.w means orange. It can be seen as a warning warning. Generally, w e need to pay attention to optimizing Android code and output Log.e information after selecting it.  

5. Log.e is red. You can think of error error. Only the red error information is displayed here. These errors need to be analyzed carefully to check the stack information.

public class MyLog {
    
    private static Boolean MYLOG_SWITCH = true; // Log file master switch
    private static Boolean MYLOG_WRITE_TO_FILE = true;// Log write file switch
    private static char MYLOG_TYPE = 'v';// Input log type, w represents only output alarm information, v represents output all information
    private static String MYLOG_PATH_SDCARD_DIR = "/sdcard/kantu/log";// The path of log file in sdcard
    private static int SDCARD_LOG_FILE_SAVE_DAYS = 0;// The maximum number of days to save log files in sd card
    private static String MYLOGFILEName = "Log.txt";// Log file name of this type of output
    private static SimpleDateFormat myLogSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// Output format of log
    private static SimpleDateFormat logfile = new SimpleDateFormat("yyyy-MM-dd");// Log file format
    public Context context;

    public static void w(String tag, Object msg) { // Warning message
        log(tag, msg.toString(), 'w');
    }

    public static void e(String tag, Object msg) { // error message
        log(tag, msg.toString(), 'e');
    }

    public static void d(String tag, Object msg) {// debug information
        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');
    }

    /**
     * Output log according to tag, msg and level
     * @param tag
     * @param msg
     * @param level
     */
    private static void log(String tag, String msg, char level) {
        if (MYLOG_SWITCH) {//Log file master switch
            if ('e' == level && ('e' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { // Output error message
                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)//Log write file switch
                writeLogtoFile(String.valueOf(level), tag, msg);
        }
    }

    /**
     * Open log file and write log
     * @param mylogtype
     * @param tag
     * @param text
     */
    private static void writeLogtoFile(String mylogtype, String tag, String text) {// New or open log file
        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("create file", "create file");
        File file = new File(dirsFile.toString(), needWriteFiel + MYLOGFILEName);// MYLOG_PATH_SDCARD_DIR
        if (!file.exists()) {
            try {
                //Create files in the specified folder
                file.createNewFile();
            } catch (Exception e) {
            }
        }

        try {
            FileWriter filerWriter = new FileWriter(file, true);// The latter parameter indicates whether to connect the original data in the file without overwriting.
            BufferedWriter bufWriter = new BufferedWriter(filerWriter);
            bufWriter.write(needWriteMessage);
            bufWriter.newLine();
            bufWriter.close();
            filerWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Delete established log files
     */
    public static void delFile() {// Delete log file
        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();
        }
    }

    /**
     * Get the date a few days before the current time to get the name of the log file to be deleted
     */
    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();
    }
}

Note: you also need to add permissions in the AndroidManifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Reference: https://www.cnblogs.com/jeffen/p/6828569.html

Keywords: Oracle Android xml

Added by DiscoTrio on Sat, 19 Oct 2019 21:54:34 +0300