6

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

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

但是,当我尝试使用功能 sink() 拆分消息连接时,出现以下错误:

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

是否有任何解决方法或替代解决方案?

谢谢

4

1 回答 1

0

所以,我尝试使用split = Tin 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将您的错误和警告消息打印到控制台。

于 2018-01-02T19:23:53.713 回答