Dana
2025-12-03 60fde3e5055390b95dcfff2252f4df84c4942822
app/src/main/java/com/anyun/h264/FileLoggingTree.java
@@ -5,11 +5,13 @@
import timber.log.Timber;
import java.io.File;
import java.io.FileFilter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
/**
 * Timber Tree implementation that logs to files.
@@ -19,6 +21,8 @@
    private static final String LOG_DIR = "nvlog";
    private static final String LOG_PREFIX = "h264_";
    private static final String LOG_SUFFIX = ".log";
        // 日志文件保留天数
        private static final int LOG_RETENTION_DAYS = 3;
    private static final String DATE_FORMAT = "yyyyMMdd";
    private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
    
@@ -36,6 +40,8 @@
            // Check if we need to update the log file (new day)
            if (!logFileName.equals(currentLogFile)) {
                currentLogFile = logFileName;
                // 新的一天,顺便清理过期日志文件
                cleanupExpiredLogFiles(LOG_RETENTION_DAYS);
            }
            
            File logFile = getLogFile(logFileName);
@@ -88,6 +94,50 @@
        } catch (IOException e) {
            Log.e("FileLoggingTree", "Error getting log file", e);
            return null;
        }
    }
    /**
     * 清理超出保留天数的日志文件
     */
    private void cleanupExpiredLogFiles(int retentionDays) {
        if (retentionDays <= 0) {
            return;
        }
        try {
            File logDir = new File(Environment.getExternalStorageDirectory(), LOG_DIR);
            if (!logDir.exists() || !logDir.isDirectory()) {
                return;
            }
            long retentionMillis = TimeUnit.DAYS.toMillis(Math.max(1, retentionDays));
            long cutoffTime = System.currentTimeMillis() - retentionMillis;
            File[] files = logDir.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    String name = pathname.getName();
                    return name.startsWith(LOG_PREFIX) && name.endsWith(LOG_SUFFIX);
                }
            });
            if (files == null || files.length == 0) {
                return;
            }
            for (File file : files) {
                if (file.lastModified() < cutoffTime) {
                    boolean deleted = file.delete();
                    if (deleted) {
                        Log.i("FileLoggingTree", "Deleted expired log file: " + file.getAbsolutePath());
                    } else {
                        Log.w("FileLoggingTree", "Failed to delete expired log file: " + file.getAbsolutePath());
                    }
                }
            }
        } catch (Exception e) {
            Log.e("FileLoggingTree", "Error cleaning up expired log files", e);
        }
    }
    
@@ -144,3 +194,4 @@
    }
}