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

TMS*_*TMS 3 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
Run Code Online (Sandbox Code Playgroud)

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

TMS*_*TMS 5

差不多明白了,但它非常复杂,而且非常烦人,与标准输出不同,消息输出无法拆分,即重定向到文件并同时保留在输出中(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)
Run Code Online (Sandbox Code Playgroud)

如果我尝试

sink(tmpFD, type = "message", split = TRUE) 
Run Code Online (Sandbox Code Playgroud)

它说

sink(tmpFD, type = "message", split = TRUE) 中的错误:无法拆分消息连接

这很烦人!