R Programming – How to Capture install.packages Output in R with sink()

r

I'd like to capture all output and errors when installing a packages. The steps when installing a package, however, do not seem to be captured by the sink() command. Here's an example:

A main.R file:

fp <- file("test.log", open = 'wt')
sink(fp, type = 'output')
sink(fp, type = 'message')
install.packages("stringr")
sink(type = 'message')
sink()

Using R -q -f main.R to run the file, I see the following in my console:

-> % R -q -f main.R
> fp <- file("test.log", open = 'wt')
> sink(fp, type = 'output')
> sink(fp, type = 'message')
> install.packages("stringr")
* installing *source* package ‘stringr’ ...
** package ‘stringr’ successfully unpacked and MD5 sums checked
** using staged installation
** R
** data
*** moving datasets to lazyload DB
** inst
** byte-compile and prepare package for lazy loading
** help
*** installing help indices
*** copying figures
** building package indices
** installing vignettes
** testing if installed package can be loaded from temporary location
** testing if installed package can be loaded from final location
** testing if installed package keeps a record of temporary installation path
* DONE (stringr)
> sink(type = 'message')
> sink()
>

The contents of test.log:

Installing package into ‘/home/bam/.local/share/R/R_library/library’
(as ‘lib’ is unspecified)
trying URL 'https://cloud.r-project.org/src/contrib/stringr_1.5.1.tar.gz'
Content type 'application/x-gzip' length 176599 bytes (172 KB)
==================================================
downloaded 172 KB


The downloaded source packages are in
    ‘/tmp/Rtmpp0Vylj/downloaded_packages’

Why aren't the console lines prepended with a star (*) included in the log file?

Best Answer

You can use keep.outputs

install.packages("stringr", keep.outputs=TRUE)

from the help

if true, keep the outputs from installing source packages in the current working directory, with the names of the output files the package names with ‘.out’ appended ...

Note, instead of TRUE can be a character string of the directory where to save the output.


Also, there are several warnings and keep-in-minds regarding the usage of sink, like

Sink-ing the messages stream should be done only with great care.

and

Do not sink the messages stream unless you understand the source code implementing it ...

Open and closing connections can be tricky and error prone, plus there might be operating system pitfalls and specificities etc.

Related Question