How to capture warnings using console output?

I am trying to capture the full console log of my R script. I want the chronological order of everything, warnings are printed as they appear. I tried this:

options(warn = 1) tmpSinkfileName <- tempfile() sink(tmpSinkfileName, split = TRUE) cat("Doing something\n") warning("Hi here") cat("Doing something else\n") warning("Hi there") sink() console.out <- readChar(tmpSinkfileName, file.info(tmpSinkfileName)$size) unlink(tmpSinkfileName) cat(console.out) # Doing something # Doing something else warnings() # NULL 

but unfortunately there are no warnings in console.out . How can i do this? According to the docs, options(warn = 1) should print warnings as they occur. Unfortunately, they were not captured by sink() .

+2
source share
2 answers

Almost everything, but itโ€™s quite complicated, and itโ€™s rather annoying that, unlike standard output, the message output cannot be split, that is, redirected to a file and stored at the output at the same time (behavior in the UNIX tick)!

 options(warn = 1) tmpSinkfileName <- tempfile() tmpFD <- file(tmpSinkfileName, open = "wt") sink(tmpFD, split = TRUE) sink(tmpFD, type = "message") cat("Doing something\n") warning("Hi here") cat("Doing something else\n") warning("Hi there") sink(type = "message") sink() console.out <- readChar(tmpSinkfileName, file.info(tmpSinkfileName)$size) unlink(tmpSinkfileName) cat(console.out) 

If i try

 sink(tmpFD, type = "message", split = TRUE) 

it says

Error in the receiver (tmpFD, type = "message", split = TRUE): it is not possible to share the connection with the message

which is very annoying!

+3
source

I wrote the following function to record output and messages:

 create_log <- function(logfile_name, path) { if (file.exists(paste0(path, logfile_name))) { file.remove(paste0(path, logfile_name)) } fid <- file(paste0(path, logfile_name), open = "wt") sink(fid, type = "message", split = F) sink(fid, append = T, type = "output", split = T) warning("Use closeAllConnections() in the end of the script") } 
+3
source

Source: https://habr.com/ru/post/1012817/


All Articles