我正在尝试将 R 脚本的错误和警告记录到外部文件中。同时我希望能够在 RStudio 的控制台中看到错误和警告(对开发和调试有用)。我正在尝试使用以下代码:
logfile <- file("my_file_path", open="wt")
sink(logfile, type="message", split = TRUE)
Run Code Online (Sandbox Code Playgroud)
但是当我尝试使用函数 sink() 拆分消息连接时,出现以下错误:
Error in sink(logfile, type = "message", split = TRUE) :
cannot split the message connection
Run Code Online (Sandbox Code Playgroud)
是否有任何解决方法或替代解决方案?
谢谢
所以,我尝试使用split = T
in 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)
Run Code Online (Sandbox Code Playgroud)
它向控制台提供了输出:-
[1] "Error: object 'a' not found"
[2] "Warning message:"
[3] "this is a warning message. please ignore "
Run Code Online (Sandbox Code Playgroud)
因此,上面的代码将错误和警告消息转移到日志文件中,并将其打印在控制台中。
您可以sink
正常使用,然后用于readLines
将错误和警告消息打印到控制台。