5

I'd like to capture warnings in R to a file and then have the normal warning code take over. Specifically, I'm wanting to log all errors and warnings to one or two files. For errors, I can make it work by adding a logging function to the error option. But, I can't find the same way to do that for warnings. I think that the answer lies within the warning.expression option, but I can't make it work.

What I'm trying right now is below. All of the errors get logged to the file "errors.txt", but the only thing in "warnings.txt" is a bunch of blank lines (the text of the message is not saved, but it is adding a line with each warning).

For my solution, tryCatch isn't a reasonable option because of the complexity of the legacy code that underlies the options and because tryCatch stops execution at the warning.

logger.error <- function(file) {
  if (missing(file)) {
    stop("A filename must be given")
  }
  function() {
    cat(geterrmessage(), "\n", file=file, sep="", append=TRUE)
  }
}

logger.warning <- function(file) {
  if (missing(file)) {
    stop("A filename must be given")
  }
  function() {
    msg <- paste(names(warnings()), collapse="\n")
    cat("Warning: ", msg, "\n",
        file=file, sep="", append=TRUE)
  }
}

options(error=logger.error("errors.txt"),
        warning.expression=quote(logger.warning("warnings.txt")()),
        warn=1)

stop("test error")
warning("test warning")
a <- function(x) {
  if (x < 0) {
    stop("x cannot be < 0")
    print("a")
  }
  if (x < 10) {
    print("b")
    warning("x should not be < 10")
    print("c")
  }
  warning("This is a useless function")
  print("d")
}
a(-1)
a(1)
tryCatch(a(1),
         warning=function(w) {
           cat("A warning: ", w$message, "\n")
         },
         error=function(e) {
           cat("An error: ", e$message, "\n")
         })
Bill Denney
  • 766
  • 1
  • 6
  • 21
  • There has been [some discussion](https://github.com/zatonovo/futile.logger/issues/36) about that in `futile.logger`, though there is no indication of attempted implementation. [`loggr`](https://github.com/smbache/loggr) may be sufficient for you. Otherwise, I think using `tryCatch` will be insufficient, you'd likely need `withCallingHandlers`/`withRestarts`. – r2evans Feb 25 '17 at 22:16
  • Thanks for the pointers to those two. It looks like loggr may have an alternate solution, and I guess it means that what I'm looking for may not exist in base R. – Bill Denney Feb 26 '17 at 22:40
  • You could also turn warnings into errors: `options(warn=2)` https://stackoverflow.com/questions/8217901/breaking-loop-when-warnings-appear-in-r – petermeissner Aug 10 '17 at 04:25

0 Answers0