4

I have written an R function that downloads a list of files from an official statistics website. Some of the downloads fail and I would like to keep track of the error message.

This answer suggest using sink(logfilename, type="message") to divert error messages to a text file but the sink help page says:

"Do not sink the messages stream unless you understand the source code implementing it and hence the pitfalls."

What are the pitfalls and is there an alternative to using sink?

Paul Rougieux
  • 10,289
  • 4
  • 68
  • 110

1 Answers1

4

I'm sure of all of the pitfalls, I've read some people having trouble with sink not releasing file access to a log file, and you could potentially forget to reset sink to output back to console instead of the log file, which could potentially corrupt your log file. But you should be able to generate an error log by running your code to download the files through a try-catch block and writing out the error messages similar to below.

log.path <- # Path to log file

tryCatch({
  # Code to attempt
  log(q)

}, error = function(err.msg){
             # Add error message to the error log file
             write(toString(err.msg), log.path, append=TRUE)
          }
)
Matt Jewett
  • 3,249
  • 1
  • 14
  • 21
  • Thanks, `download.file` returns both an error and a warning. I have added `warning = function(warningcondition){ # Add warning message to the log file write(toString(warningcondition), logfile, append=TRUE)` to the `tryCatch` block and now it writes the warning to the logfile, but it doesn't write the error any more. I have written a reproducible example with 2 functions in [this gist](https://gist.github.com/paul4forest/bfeb84d3d116f108d3cda3e497181a57). How can my function capture both error and warning to the log file? – Paul Rougieux Jul 12 '17 at 08:50
  • A similar question was expressed here: [Handling errors before warnings in tryCatch](https://stackoverflow.com/q/19433848/2641825) – Paul Rougieux Jul 12 '17 at 09:05