write/writeLines to multiple connections (e.g console output and log file)

240 Views Asked by At

I'm using writeLines() to create a log file, but I'd like to see the text written to the log file also in the console. Is there a way to define a connection that writes text into a file and simultaneously prints the text in the console?

Something like:

con1 <- file("log.txt", "w")
con2 <- console()

writeLines("Lorem ipsum dolor sit amet", con=c(con1, con2))

close(con1)

My solution so far needs some extra lines to do that.

con1 <- file("log.txt", "w")

log.txt <- "Lorem ipsum dolor sit amet"

writeLines(log.txt)
writeLines(log.txt, con=con1)

close(con1)

I'm wondering if there is a simpler way to do that.

1

There are 1 best solutions below

2
On

You can use the split argument to sink(). For example,

con1 <- file("log.txt", "w")
sink(con1, split = TRUE)
log.txt <- "Lorem ipsum dolor sit amet"
writeLines(log.txt)
sink()  # back to normal