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")
})