Output error/warning log (txt file) when running R script under command line Output error/warning log (txt file) when running R script under command line r r

Output error/warning log (txt file) when running R script under command line


You can use sink() to divert messages as well as warnings to a file. The trick is to set the argument type="message":

Here is an example adapted from the help for ?sink:

setwd(tempdir())## capture messages and errors to a file.zz <- file("all.Rout", open="wt")sink(zz, type="message")try(log("a"))## reset message sink and close the file connectionsink(type="message")close(zz)## Display the log filereadLines("all.Rout")[1] "Error in log(\"a\") : Non-numeric argument to mathematical function"


To close the connection with the log file you have to use sink(type="message") instead of sink() and then close(zz).