rstdoutmessagestderr

send R diagnostic messages to stdout instead stderr


Looking for an options which let me to redirect R diagnostic messages (produces by message()) to stdout, not stderr as it is by default.

message manual states:

The default handler sends the message to the stderr() connection.

So the question is how can I change this default behavior? still leaving redirection of warning() and stop() intact.

Already tried sink type='message' but it redirects all (messages, warnings, errors).

If anyone is willing to test, this is sample script exec_test.R:

print("using print")
cat("using cat\n")
message("using message")
warning("using warning")
stop("using stop")
q("no")

which then will be executed by:

Rscript exec_test.R 1>> exec_test.Rout 2>> exec_test_error.Rout

I don't what to use 2>&1 because my script produce tons of messages and very rarely the real errors so I need to store those logs in separate files.


Solution

  • While this is very likely not a best practice, you could override message with a version that writes to stdout() by default, right?

    message <- function (..., domain = NULL, appendLF = TRUE) 
    {
        args <- list(...)
        cond <- if (length(args) == 1L && inherits(args[[1L]], "condition")) {
            if (nargs() > 1L) 
                warning("additional arguments ignored in message()")
            args[[1L]]
        }
        else {
            msg <- .makeMessage(..., domain = domain, appendLF = appendLF)
            call <- sys.call()
            simpleMessage(msg, call)
        }
        defaultHandler <- function(c) {
            cat(conditionMessage(c), file = stdout(), sep = "")
        }
        withRestarts({
            signalCondition(cond)
            defaultHandler(cond)
        }, muffleMessage = function() NULL)
        invisible()
    }