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

user2348684
  • 361
  • 4
  • 17
  • 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)`. – sm925 Dec 29 '17 at 17:11
  • You're right. I didn't copy well the sample code. But the question remains valid. – user2348684 Jan 02 '18 at 09:28

1 Answers1

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.

sm925
  • 2,648
  • 1
  • 16
  • 28
  • 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... – user2348684 Jan 03 '18 at 12:00
  • 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. – sm925 Jan 07 '18 at 00:44
  • Yes, but it is so strange that there isn't any real alternative to solve the issue... – user2348684 Jan 08 '18 at 18:31
  • That's true. It's really annoying when you get an error because of that `split` thing. – sm925 Jan 08 '18 at 18:32