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

21,660

Solution 1

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 connection
sink(type="message")
close(zz)

## Display the log file
readLines("all.Rout")
[1] "Error in log(\"a\") : Non-numeric argument to mathematical function"

Solution 2

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

Share:
21,660
Joyce
Author by

Joyce

Updated on May 05, 2020

Comments

  • Joyce
    Joyce about 4 years

    If I run R script under command line (actually I run that from calling in VBA), how can I output any error/warning messages to a txt file?

  • Joyce
    Joyce almost 12 years
    However, how can I close the connection with the log file? I tried sink(), but when I want to delete the log file, I cannot delete that, as seems there is still connection. Only after I closed my R, I can delete that. How should I close the connection?
  • Jthorpe
    Jthorpe about 7 years
    This is because in the original answer, sink was not terminated with type="message" and the connection was not closed. (Fixed in the updated answer)