【问题标题】:How to write errors and warnings to a log file?如何将错误和警告写入日志文件?
【发布时间】:2017-07-11 13:41:11
【问题描述】:

我写了一个从官方统计网站下载文件列表的 R 函数。一些下载失败,我想跟踪错误消息。

This answer 建议使用sink(logfilename, type="message") 将错误消息转移到文本文件,但sink 帮助页面显示:

“除非您了解实现它的源代码,否则请不要接收消息流,从而了解其中的陷阱。”

有什么陷阱?有没有使用 sink 的替代方法?

【问题讨论】:

    标签: r


    【解决方案1】:

    我确信所有的陷阱,我读过一些人在sink 不释放对日志文件的文件访问时遇到问题,您可能会忘记重置sink 以改为输出回控制台的日志文件,这可能会损坏您的日志文件。但是您应该能够通过运行代码以通过 try-catch 块下载文件并写出类似于下面的错误消息来生成错误日志。

    log.path <- # Path to log file
    
    tryCatch({
      # Code to attempt
      log(q)
    
    }, error = function(err.msg){
                 # Add error message to the error log file
                 write(toString(err.msg), log.path, append=TRUE)
              }
    )
    

    【讨论】:

    • 谢谢,download.file 返回错误和警告。我已将warning = function(warningcondition){ # Add warning message to the log file write(toString(warningcondition), logfile, append=TRUE) 添加到tryCatch 块中,现在它将警告写入日志文件,但不再写入错误。我在this gist 中编写了一个具有 2 个函数的可重现示例。我的函数如何将错误和警告同时捕获到日志文件中?
    • 这里表达了类似的问题:Handling errors before warnings in tryCatch
    猜你喜欢
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 2013-11-26
    相关资源
    最近更新 更多