如何使用控制台输出捕获警告?

时间:2014-09-20 12:30:46

标签: r

我正在尝试捕获我的R脚本的完整控制台日志。我希望按时间顺序排列所有内容,警告会在出现时打印出来。我试过这个:

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

但不幸的是console.out中没有警告。我怎样才能做到这一点?根据文档,options(warn = 1)应该在警告出现时打印出来。不幸的是,他们没有被sink()捕获。

2 个答案:

答案 0 :(得分:4)

几乎得到它,但它非常复杂,而且非常烦人,与标准输出不同,消息输出无法拆分,即重定向到文件并同时保存在输出中(UNIX tee行为)!

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)

如果我尝试

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

它说

  

接收器错误(tmpFD,类型=&#34;消息&#34;,split = TRUE):无法拆分   消息连接

这很烦人!

答案 1 :(得分:3)

我编写了以下函数来捕获输出和消息:

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")
}