How to create periodically send text to a "log file" while printing normal output to console?

See ?cat. You can open a file connection to your log file and specify that in your cat call. When you don't specify a file name or connection it will print to the console.

As you say, don't use sink() as it will make the log file the default connection. Rather, open a named connection with file().

> log_con <- file("test.log")
> cat("write to log", file = log_con) # creates file and writes to it
> cat("write to console") # prints to console
write to console

The above results in a log file with the line "write to log" and "write to console" printed on the console.

If you need to append to your log file, set append = TRUE and use the file name instead of the file() connection.

> cat("add to log", file = "test.log", append = TRUE)

To open the log file in "append" mode:

log_con <- file("test.log",open="a")

Figured it out, thanks to shujaa and BigFinger. To summarize, here is how you would do it with my example code:

log_con <- file("/filepath/log.txt", open="a")

for (i in 1:100)
{
cat("loop begins", file = log_con, sep="\n")
a <- rnorm(n = 100, mean = i, sd = 5)
print(mean(a))
cat("single loop completed", file = log_con, sep="\n")
}

close(log_con)

Tags:

R