R sink(): Error, cannot split the message connection
Asked Answered
H

1

7

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

Humiliate answered 28/12, 2017 at 15:39 Comment(2)
Sink's first argument should be a connection to a file. So, it should be something like this file_con <- file("my_file_path", open = "a") and then you do sink(logfile, type="message", split = TRUE).Metalinguistics
You're right. I didn't copy well the sample code. But the question remains valid.Humiliate
M
0

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.

Metalinguistics answered 2/1, 2018 at 19:23 Comment(4)
It's a workaround but it's not so useful for debugging, when you need to get the warnings and errors before running all the script. I can't believe there isn't any real alternative for this problem...Humiliate
It is a work around. I have mentioned that in my answer. It would be helpful if your script doesn't take lot of time to complete. If takes too long to complete, eventually you'll get the desired output.Metalinguistics
Yes, but it is so strange that there isn't any real alternative to solve the issue...Humiliate
That's true. It's really annoying when you get an error because of that split thing.Metalinguistics

© 2022 - 2024 — McMap. All rights reserved.