R/log.R

#' Retrieve the name of the log file
#'
#' @export
#' @param path the path to the file
#' @param roll logical, if TRUE then roll (rotate the log)
#' @param ... further arguments for \code{log_roll()}
#' @return the fully qualified path
log_file <- function(path = obpg_path(), roll = TRUE, ...){
    filename = file.path(path, "log")
    if (roll) s = log_roll(filename, ...)
    filename
}


#' Roll the log file to a new one based upon file size
#'
#' @export
#' @param filename the name of the file
#' @param max_size numeric the maximum log file size in bytes to trigger rotation
#' @return the size of the current log file (possibly rotated)
log_roll <- function(filename = log_file(), max_size = 1e5){

    fi = file.info(filename)
    if (fi$size[1] > max_size){
        ff  = list.files(dirname(filename), pattern = glob2rx("log.*"),
                         full.names = TRUE, recursive = FALSE)
        dst = paste0(filename, ".", length(ff)+1)
        ok  = file.rename(filename, dst)
        cat("[New Log File]", as.character(Sys.time()), "\n",
            file = filename, append = FALSE)
        fi = file.info(filename)
    }

    fi$size[1]
}


#' Retrieve the tail end of the OBPG log
#'
#' @export
#' @param filename the path to the log file
#' @param n the number of lines to retrieve - default 20
#' @return character vector
log_tail <- function(filename = log_file(), n = 20){
    cmd = sprintf("tail -n%i %s", n, filename)
    system(cmd, intern = TRUE)
}
btupper/obpgtools documentation built on May 13, 2019, 8:42 a.m.