From 820fca76ccb040f831278476f674549ba37190b8 Mon Sep 17 00:00:00 2001 From: Ryan Erickson Date: Wed, 31 Aug 2022 10:07:12 -0500 Subject: [PATCH] logging: fs backend: only delete old files if necessary During initialization of the FS backed, the oldest file is always deleted. Fix this to prevent throwing away useful historic logs. If there is space left in the newest file, append to it instead of creating a new file and removing the oldest. Signed-off-by: Ryan Erickson --- subsys/logging/log_backend_fs.c | 34 ++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/subsys/logging/log_backend_fs.c b/subsys/logging/log_backend_fs.c index 635b7ddfe7e..cbde147f949 100644 --- a/subsys/logging/log_backend_fs.c +++ b/subsys/logging/log_backend_fs.c @@ -263,6 +263,7 @@ static int allocate_new_file(struct fs_file_t *file) int curr_file_num; struct fs_dirent ent; char fname[MAX_PATH_LEN]; + off_t file_size; assert(file); @@ -339,14 +340,33 @@ static int allocate_new_file(struct fs_file_t *file) curr_file_num = newest; - if (file_ctr >= 1) { - curr_file_num++; - if (curr_file_num > MAX_FILE_NUMERAL) { - curr_file_num = 0; - } + /* Is there space left in the newest file? */ + snprintf(fname, sizeof(fname), "%s/%s%04d", CONFIG_LOG_BACKEND_FS_DIR, + CONFIG_LOG_BACKEND_FS_FILE_PREFIX, curr_file_num); + rc = fs_open(file, fname, FS_O_CREATE | FS_O_WRITE | FS_O_APPEND); + if (rc < 0) { + goto out; + } + file_size = fs_tell(file); + if (file_size < CONFIG_LOG_BACKEND_FS_FILE_SIZE) { + /* There is space left to log to the latest file, no need to create + * a new one or delete old ones at this point. + */ + if (file_ctr == 0) { + ++file_ctr; + } + backend_state = BACKEND_FS_OK; + goto out; + } else { + fs_close(file); + if (file_ctr >= 1) { + curr_file_num++; + if (curr_file_num > MAX_FILE_NUMERAL) { + curr_file_num = 0; + } + } + backend_state = BACKEND_FS_OK; } - - backend_state = BACKEND_FS_OK; } else { fs_close(file);