Andrews writes and log file management

In project development, often you need to debug and difficult investigation by the log. The log is a persistent online app development really necessary. Android Log class itself, is the log output to the console, and can not output to a file. This article describes a simple and practical LogUtils usage and implementation of logic can be written to a log Log in, give you a reference. Source here: log-to-File .
LogUtils using the class initialization code needs to be added in the Application onCreate as follows:

private void initLog() {
    LogUtils.setLogDir(YiqiConfig.getLogFolderPath());
    if (EnvironmentUtils.getVersionName().toLowerCase().contains("beta")) {
        LogUtils.setLogLevel(LogUtils.LogLevel.DEBUG);
    } else {
        // 为了保护隐私和保证log的整洁,正式版上只打比warn高的log,即warn, error和assert
        LogUtils.setLogLevel(LogUtils.LogLevel.WARN);
    }
}

Usage and android.utils.Log same method name and parameters are one correspondence. Increased functionality is, after output to the console, but also output to a log file, and the number of log file management. The number and size of the individual log files are log files may be provided in the code.

private static final int LOG_FILES_MAX_NUM = 5; //文件最多有5个
private static final int LOG_FILE_MAX_SIZE = 1024 * 1024; //文件最大1MB

When filled with a file, create a new log file, if the number of files exceeds the maximum number, you delete the oldest log files.
The main logic of the following methods:

private File getNewLogFile() {
    File dir = new File(mLogFileDir);
    File[] files = dir.listFiles(fileFilter);
    if (files == null || files.length == 0) {
        // 创建新文件
        return createNewLogFile();
    }
    List<File> sortedFiles = sortFiles(files);
    if (files.length > LOG_FILES_MAX_NUM) {
        // 删掉最老的文件
        FileUtils.delete(sortedFiles.get(0));
    }
    // 取最新的文件,看写没写满
    File lastLogFile = sortedFiles.get(sortedFiles.size() - 1);
    if (lastLogFile.length() < LOG_FILE_MAX_SIZE) {
        return lastLogFile;
    } else {
        // 创建新文件
        return createNewLogFile();
    }
}

First, determine whether there is not any log file, if it is directly create a new log file; if the log file already exists, determine whether the current number of log files exceeds the maximum number, if exceeded, then delete the oldest log file; and finally judgment if the latest file is full, not filled directly written in the document, filled, then you create a new file.



Author: InnerNight
link: https: //www.jianshu.com/p/548c7b18397e
Source: Jane book
Jane book copyright reserved by the authors, are reproduced in any form, please contact the author to obtain authorization and indicate the source.

Published 442 original articles · won praise 77 · views 1 million +

Guess you like

Origin blog.csdn.net/rnZuoZuo/article/details/95738679