Skip to content

Commit 301ee70

Browse files
Defenses around adding log files for postproc
1 parent e9b745f commit 301ee70

1 file changed

Lines changed: 25 additions & 4 deletions

File tree

‎R/postprocess_subject.R‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -85,13 +85,34 @@ postprocess_subject <- function(in_file, cfg=NULL) {
8585

8686
# force log file to be in the right directory
8787
log_file <- file.path(log_dir, basename(cfg$log_file))
88-
dir.create(dirname(log_file), recursive = TRUE, showWarnings = FALSE)
88+
log_dir_exists <- dir.create(dirname(log_file), recursive = TRUE, showWarnings = FALSE) || dir.exists(dirname(log_file))
89+
if (!log_dir_exists || file.access(dirname(log_file), 2) != 0) {
90+
# fall back to a writable temp directory if the requested log dir is unavailable
91+
log_dir <- file.path(tempdir(), "postprocess_logs", glue("sub-{input_bids_info$sub}"))
92+
dir.create(log_dir, recursive = TRUE, showWarnings = FALSE)
93+
log_file <- file.path(log_dir, basename(cfg$log_file))
94+
}
95+
if (!file.exists(log_file)) file.create(log_file)
8996

9097
lg <- lgr::get_logger_glue(c("postprocess", input_bids_info$sub))
91-
if ("postprocess_log" %in% names(lg$appenders)) {
92-
lg$remove_appender("postprocess_log")
98+
existing_appenders <- names(lg$appenders)
99+
stale_appenders <- existing_appenders[grepl("^postprocess_log", existing_appenders)]
100+
if (length(stale_appenders) > 0) {
101+
for (app_name in stale_appenders) {
102+
try(lg$appenders[[app_name]]$close(), silent = TRUE)
103+
try(lg$remove_appender(app_name), silent = TRUE)
104+
}
93105
}
94-
lg$add_appender(lgr::AppenderFile$new(log_file), name = "postprocess_log")
106+
appender <- tryCatch(
107+
lgr::AppenderFile$new(log_file),
108+
error = function(e) {
109+
fallback <- file.path(tempdir(), basename(log_file))
110+
dir.create(dirname(fallback), recursive = TRUE, showWarnings = FALSE)
111+
if (!file.exists(fallback)) file.create(fallback)
112+
lgr::AppenderFile$new(fallback)
113+
}
114+
)
115+
lg$add_appender(appender, name = "postprocess_log")
95116

96117
# quick header check to avoid 3D or single-volume inputs
97118
hdr <- suppressWarnings(tryCatch(RNifti::niftiHeader(in_file), error = function(...) NULL))

0 commit comments

Comments
 (0)