在R中运行多个脚本组件时将错误消息附加到日志文件

时间:2017-12-18 15:19:43

标签: r error-handling

我正在尝试将脚本的错误消息写入日志文件。它适用于我:

test <- file("error_file.log", open = "wt")
sink(test, type = "message")
try(data <- read.delim("genes2.txt",
                   header = TRUE,
                   as.is = TRUE))
sink(type = "message", append = TRUE)
close(test)

但是,当我向脚本添加其他组件时,它不会附加错误消息。在这种情况下,两个输入文件都不存在,并且应为每个文件提供“无此文件目录”。这是我对两个输入文件的尝试:

enter code heretest <- file("error_file.log", open = "wt")

sink(test, type = "message")

try(data <- read.delim("genes2.txt",
                       header = TRUE,
                       as.is = TRUE))

sink(type = "message", append = TRUE)
close(test)

test2 <- file("error_file.log", open = "wt")
sink(test2, type = "message")

try(variables <- read.delim("Book3.txt",
                            header = TRUE, 
                            as.is = TRUE,
                            check.names = FALSE,
                            text = TRUE,
                            na.strings = c("", NA)))

sink(type = "message", append = TRUE)
close(test2)

谢谢!

P.S。是否可以为每个try()自定义我自己的错误消息?

2 个答案:

答案 0 :(得分:1)

尝试使用它,它会将这两个消息附加到error_file.log: -

test <- file("error_file.log", open = "wt")
sink(test, append = TRUE, type = "message")


try(data <- read.delim("genes2.txt",
                       header = TRUE,
                       as.is = TRUE))


try(variables <- read.delim("Book3.txt",
                            header = TRUE, 
                            as.is = TRUE,
                            check.names = FALSE,
                            text = TRUE,
                            na.strings = c("", NA)))


sink(type = "message")

因此,错误文件将包含: -

Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
  cannot open file 'genes2.txt': No such file or directory
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
  cannot open file 'Book3.txt': No such file or directory

我希望这能解决你的问题。

诀窍就是打开你的日志文件并在开始时下沉一次。并且,最后关闭。

答案 1 :(得分:0)

使用@suchait的有效答案作为基础,您可以通过以下方式自定义错误消息:

test <- file("error_file.log", open = "wt")
sink(test, append = TRUE, type = "message")

tryCatch(data <- read.delim("genes2.txt", header = TRUE, as.is = TRUE),
         error = function(e) {
           # replace one specific error message with another one
           if (grepl("cannot open", e$message, fixed = TRUE))
             # using "message" instead of "print" since you are sinking into type "message" (not "output")
             message("Customized error message 1: The file could not be opened\n")
           else
             message(e$message)
         }
         # If you wanted to replace the warnings too you will run into big problems:
         # tryCatch stops the execution and the error handler above is never called
         # causing the log to be empty. Conclusion: Don't reinvent the wheel and
         # use a suitable logging framework (e. g. the package "futile.logger")...
         # , warning = function(w) {return("Warning ignored...")}  # ignore warnings
)

tryCatch(variables <- read.delim("Book3.txt", header = TRUE, as.is = TRUE, check.names = FALSE, text = TRUE, na.strings = c("", NA)),
         error = function(e) {
           # Always write your specific error message (+ the original message if you want)
           message(paste("Customized error message 2: The file could not be opened. Details:", e$message, "\n"))
         }
)

sink(type = "message")

如果你想更换警告,你会遇到问题(请参阅上面代码中的我的评论),解决方案将是一个更复杂的代码(使用withCallingHandlers + try)< / p>

因此,我认为最好使用现有的日志框架,例如包futile.logger(参见函数ftry),而不是重新发明轮子并遇到许多问题。您可以设置“严重性级别”,然后记录e。 G。只有错误但没有警告...

如果您想将错误处理与日志记录相结合,则

tryCatch是R中的野兽(有关详细信息,请参阅R: Catch errors and continue execution after logging the stacktrace (no traceback available with tryCatch)以及一长串相关的SO问题)......

如果您要将自动日志记录添加到trytryCatch,则可以使用包tryCatchLoghttps://github.com/aryoda/tryCatchLog)。出于合规原因:我是该软件包的作者......