Search code examples
rerror-logging

Error Handling and logging in R


I have written a function in R to print any message both to log file and console. But if there is any unexpected error while running the code, then error is displayed only to console. Is there any way to write error message to both console and log file? Here is the function..

log_con <- file("Text1.txt", open="a")

loggerfn<-function(Message,LogConnection=log_con){
  cat(Message, file = LogConnection)
  cat(Message)
}

Here is the sample code to...

for (i in 1:10)
 {
  loggerfn("loop begins\n",log_con)
   a <- rnorm(n = 100, mean = i, sd = 5)
   loggerfn(mean(a),log_con)
   loggerfn("loop Completed\n",log_con)
   if(i==8){
     sdfs
   }
 }

In above code I have intentionally introduced error by providing undefined object sdfd.Below provided Error message is shown only in console, is there any way to write error message to both console and logfile?

Error: object 'sdfs' not found

Solution

  • use sink() to divert messages as well as warnings to a file. The trick is to set the argument type="message"

    refer http://www.statmethods.net/interface/io.html and Output error/warning log (txt file) when running R script under command line https://stat.ethz.ch/R-manual/R-devel/library/base/html/sink.html

    The sink( ) function defines the direction of the output.

    Description

    sink diverts R output to a connection (and stops such diversions).

    sink.number()
    

    reports how many diversions are in use.

    sink.number(type = "message") reports the number of the connection currently being used for error messages. Usage

    sink(file = NULL, append = FALSE, type = c("output", "message"),
         split = FALSE)
    
    sink.number(type = c("output", "message"))
    

    direct output to a file

    sink("myfile", append=FALSE, split=FALSE)
    

    return output to the terminal

    sink()
    

    The append option controls whether output overwrites or adds to a file. The split option determines if output is also sent to the screen as well as the output file.

    Here are some examples of the sink() function.

    output directed to output.txt in c:\projects directory. output overwrites existing file. no output to terminal.

    sink("c:/projects/output.txt")
    

    output directed to myfile.txt in cwd. output is appended to existing file. output also send to terminal.

    sink("myfile.txt", append=TRUE, split=TRUE)
    

    When redirecting output, use the cat( ) function to annotate the output.