java—添加文件大小管理逻辑(方法)来管理存储在设备内部存储器中的log.txt文件的大小

gg0vcinb  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(193)

我们有一个日志管理系统,可以在应用程序运行时在文件上打印logcat。每天都有一个新文件,并且删除前一天的日志文件。问题是,如果用户长时间使用该应用程序,日志文件的大小会变得相当大,并且可以达到gbs。
我们需要一个日志管理系统来避免这种情况,以便始终以合理的大小更新日志,最好小于150-200 mb。日志文件是保存logcat的简单文本文件。从文件中的每一行都对应一个特定的时间开始,我就在想,当文件达到150MB时,会删除前x行,以便减小文件大小,保留最新的日志,重要的日志我们只需要保留一天的文件。我们不需要昨天的档案
逻辑可以是:

if today 20201128 delete 20201127
   create a directory with the datum "20201128"
   create file 20201128_11_52 in it

创建控制系统

while file < 200 mb do nothing
then
open new file logs in it
close old file
zip old file
if 20201128 > 2 GB sent mail to us,
somethis is going worong

下面是我们正在使用的当前代码

public class startLogging {
​
    static String globalLogName = "logcat-" + getCurrentDate() + "-.txt";
​
    public static void startLog(){
​
        if (isExternalStorageWritable()) {
            //Delete old logs
            deleteOldLogs();
​
            File logDirectory      = new File(Environment.getExternalStorageDirectory().getPath() +"/ElenaLogs/");
            File logFile           = new File(logDirectory, globalLogName );
​
​
            // create log folder
            if (!logDirectory.exists()) {
                logDirectory.mkdir();
            }
​
            // clear the previous logcat and then write the new one to the file
            try {
                Process process     = Runtime.getRuntime().exec("logcat -c");
                process             = Runtime.getRuntime().exec("logcat -f " + logFile);
            } catch ( IOException e ) {
                e.printStackTrace();
            }
​
        }
    }
​
    private static boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state);
    }
​
    private static String getCurrentDate(){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
        Date date = new Date();
        //Return the date in this format: 20200515, that is a larger number every day, more easy to delete old logs
        return formatter.format(date).replace("/", "");
    }
​
    public static String getCurrentLogPath(){
        return Environment.getExternalStorageDirectory().getPath() +"/ElenaLogs/" + globalLogName;
    }
​
    private static String[] getFilesInDir(){
        //Get all the files in the ElenaLogs dir
        String[] fileNames;
        File f = new File(Environment.getExternalStorageDirectory().getPath()+"/ElenaLogs");
        fileNames = f.list();
        return fileNames;
    }
​
    private static boolean deleteFile(String dateToDelete){
​
        String globalPath           = Environment.getExternalStorageDirectory().getPath() +"/ElenaLogs/";
​
        String fileToDelete         = "logcat-"+dateToDelete+"-.txt";
        String pathFile             = globalPath + fileToDelete;
​
        String zipToDelete          = "logcat-"+dateToDelete+"-.zip";
        String pathZip             = globalPath + zipToDelete;
​
        File filetoDelete               = new File(pathFile);
        File ziptoDelete                = new File(pathZip);
​
        ziptoDelete.delete();
​
        return filetoDelete.delete();
    }
​
    private static void deleteOldLogs(){
​
        String          date                    = getCurrentDate();
        int             dateNumber              = Integer.parseInt(date);
        String[]        allLogs                 = getFilesInDir();
​
        try{
            for (String logFileName : allLogs) {
​
                int logDate = Integer.parseInt(logFileName.split("-")[1]);
​
                if (logDate < dateNumber) {
                    //Old file, delete
                    deleteFile(String.valueOf(logDate));
                }
​
            }
        }catch (NullPointerException e){
            e.printStackTrace();
        }
​
​
    }
​
    public static String getPathForEmail(){
​
        String zippedFilename   =   globalLogName.replace(".txt", ".zip");
        String zippedFilePath   =   Environment.getExternalStorageDirectory().getPath() + "/ElenaLogs/" + zippedFilename;
​
        //Zip the current log file
        if (zipFileAtPath(getCurrentLogPath(), zippedFilePath)){
            return zippedFilePath;
        }else {
            return getCurrentLogPath();
        }
​
    }
​
    /**Zips the logs**/
​
    public static boolean zipFileAtPath(String sourcePath, String toLocation) {
        final int BUFFER = 2048;
​
        File sourceFile = new File(sourcePath);
        try {
            BufferedInputStream origin = null;
            FileOutputStream dest = new FileOutputStream(toLocation);
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
                    dest));
            if (sourceFile.isDirectory()) {
                zipSubFolder(out, sourceFile, sourceFile.getParent().length());
            } else {
                byte data[] = new byte[BUFFER];
                FileInputStream fi = new FileInputStream(sourcePath);
                origin = new BufferedInputStream(fi, BUFFER);
                ZipEntry entry = new ZipEntry(getLastPathComponent(sourcePath));
                entry.setTime(sourceFile.lastModified()); // to keep modification time after unzipping
                out.putNextEntry(entry);
                int count;
                while ((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
            }
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
​
​
    private static void zipSubFolder(ZipOutputStream out, File folder,
                              int basePathLength) throws IOException {
​
        final int BUFFER = 2048;
​
        File[] fileList = folder.listFiles();
        BufferedInputStream origin = null;
        for (File file : fileList) {
            if (file.isDirectory()) {
                zipSubFolder(out, file, basePathLength);
            } else {
                byte data[] = new byte[BUFFER];
                String unmodifiedFilePath = file.getPath();
                String relativePath = unmodifiedFilePath
                        .substring(basePathLength);
                FileInputStream fi = new FileInputStream(unmodifiedFilePath);
                origin = new BufferedInputStream(fi, BUFFER);
                ZipEntry entry = new ZipEntry(relativePath);
                entry.setTime(file.lastModified()); // to keep modification time after unzipping
                out.putNextEntry(entry);
                int count;
                while ((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
                origin.close();
            }
        }
    }
​
    /*
     * gets the last path component
     *
     * Example: getLastPathComponent("downloads/example/fileToZip");
     * Result: "fileToZip"
     */
    private static String getLastPathComponent(String filePath) {
        String[] segments = filePath.split("/");
        if (segments.length == 0)
            return "";
        String lastPathComponent = segments[segments.length - 1];
        return lastPathComponent;
    }
​
}

在上面代码中的第一个方法,即startolog()中进行了大量搜索之后,我尝试实现以下逻辑。但它不起作用。

if(logFile.length()/1024*1024>150){
    Log.d(globalLogName,"greaterFileSize"+logFile.length());
    process=Runtime.getRuntime().exec("tail -n +500"+logFile.getName());
}

在startlog()中实现了上述逻辑,如下所示-

public static void startLog() {
        if (isExternalStorageWritable()) {
            //Delete old logs
            deleteOldLogs();
            File logDirectory = new File(Environment.getExternalStorageDirectory().getPath() + "/ElenaLogs/");
            File logFile = new File(logDirectory, globalLogName);
            // create log folder
            if (!logDirectory.exists()) {
                logDirectory.mkdir();
            }
            // clear the previous logcat and then write the new one to the file
            try {
                Log.d(globalLogName,"greaterFileSize"+logFile.length());
                Process process = Runtime.getRuntime().exec("logcat -c");
                process = Runtime.getRuntime().exec("logcat -f " + logFile);
                if(logFile.length()/1024*1024>150){
                    Log.d(globalLogName,"greaterFileSize"+logFile.length());
                    process=Runtime.getRuntime().exec("tail -n +500"+logFile.getName());
                }
            } catch (IOException e) {
                Log.d(globalLogName,"greaterFileSize"+logFile.length());
                e.printStackTrace();
            }
        }
    }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题