问题
I am trying to log the errors and warnings of an R script into an external file. At the same time I want to be able to see the errors and warnings in the console in RStudio (useful to develop and debug). I am trying to use the following code:
logfile <- file("my_file_path", open="wt")
sink(logfile, type="message", split = TRUE)
But when I try to split the message connection using the funciton sink() I get the following error:
Error in sink(logfile, type = "message", split = TRUE) :
cannot split the message connection
Is there any workaround or alternative solution?
Thanks
回答1:
So, I tried using split = T
in sink
.
But, it's not doing what we want it to do. It's either redirecting output to log file or throwing an error which you pointed and is not printing errors or warning messages to RStudio console.
There's a work around to your problem which might solve your problem.
I tried using this:-
# path to your log file
file_path <- "path/documents/log/log.txt"
# open a connection to your log file
file_con <- file(file_path, open = "a")
## capture warning messages and errors to log file
sink(file_con, type = "message")
## to get error and warning message
sum(a)
warning("this is a warning message. please ignore")
## revert output back to the console and close the file connection
sink(type = "message")
close(file_con)
# get all the errors and warnings from log file
readLines(file_path)
It gave an output to console:-
[1] "Error: object 'a' not found"
[2] "Warning message:"
[3] "this is a warning message. please ignore "
So, the above piece of code diverted the error and warning message to log file and printed it in console too.
You can use sink
normally and then use readLines
to print your error and warning messages to console.
来源:https://stackoverflow.com/questions/48010243/r-sink-error-cannot-split-the-message-connection