R sink():错误,无法拆分消息连接

时间:2017-12-28 15:39:18

标签: r logging sink

我正在尝试将R脚本的错误和警告记录到外部文件中。同时我希望能够在RStudio的控制台中看到错误和警告(对开发和调试很有用)。我正在尝试使用以下代码:

logfile <- file("my_file_path", open="wt")
sink(logfile, type="message", split = TRUE)

但是当我尝试使用funciton sink()拆分消息连接时,我收到以下错误:

Error in sink(logfile, type = "message", split = TRUE) : 
  cannot split the message connection

有解决方法或替代解决方案吗?

由于

1 个答案:

答案 0 :(得分:0)

所以,我尝试在split = T中使用sink

但是,它没有做我们想做的事情。它将输出重定向到日志文件或抛出您指向的错误,而不是向RStudio控制台打印错误或警告消息。

可以解决您的问题,解决您的问题。

我尝试使用它: -

# path to your log file
file_path <- "path/documents/log/log.txt"

# open a connection to your log file
file_con <- file(file_path, open = "a")

## capture warning messages and errors to log file
sink(file_con, type = "message")

## to get error and warning message 
sum(a)
warning("this is a warning message. please ignore")

## revert output back to the console and close the file connection
sink(type = "message")
close(file_con)

# get all the errors and warnings from log file
readLines(file_path)

它给控制台输出了一个: -

[1] "Error: object 'a' not found"              
[2] "Warning message:"                         
[3] "this is a warning message. please ignore "

因此,上面的代码将错误和警告消息转移到日志文件中,并将其打印在控制台中。

您可以正常使用sink,然后使用readLines将错误和警告消息打印到控制台。