I\'m creating R code for a Monte Carlo simulation of a professional sport. Because the game dynamics are very complicated and to make the debugging process simpler, I\'d like to
write("this message", file=stderr())
To open the log file in "append" mode:
log_con <- file("test.log",open="a")
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)
The library log4r seems to be more complete than an homemade one: https://github.com/johnmyleswhite/log4r
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)