打印堆栈跟踪并在R中发生错误后继续

时间:2009-12-29 15:07:15

标签: debugging r

我正在编写一些调用可能失败的其他代码的R代码。如果是这样,我想打印堆栈跟踪(以追踪出错的地方),然后继续进行。但是,traceback()函数仅提供有关未捕获异常的信息。我可以通过一个涉及tryCatch和dump.frames的相当复杂,纯粹的构造得到我想要的结果,但有没有更简单的方法呢?

8 个答案:

答案 0 :(得分:19)

我在一周前编写了这段代码,以帮助我找出主要来自非交互式R会话的错误。它仍然有点粗糙,但它打印出一个堆栈跟踪并继续。让我知道如果这是有用的,我会对你如何使这个更有用的信息感兴趣。我也可以通过更清晰的方式获取这些信息。

options(warn = 2, keep.source = TRUE, error = quote({
  # Debugging in R
  #   http://www.stats.uwo.ca/faculty/murdoch/software/debuggingR/index.shtml
  #
  # Post-mortem debugging
  #   http://www.stats.uwo.ca/faculty/murdoch/software/debuggingR/pmd.shtml
  #
  # Relation functions:
  #   dump.frames
  #   recover
  # >>limitedLabels  (formatting of the dump with source/line numbers)
  #   sys.frame (and associated)
  #   traceback
  #   geterrmessage
  #
  # Output based on the debugger function definition.

  # TODO: setup option for dumping to a file (?)
  # Set `to.file` argument to write this to a file for post-mortem debugging    
  dump.frames()  # writes to last.dump
  n <- length(last.dump)
  if (n > 0) {
    calls <- names(last.dump)
    cat("Environment:\n", file = stderr())
    cat(paste0("  ", seq_len(n), ": ", calls), sep = "\n", file = stderr())
    cat("\n", file = stderr())
  }

  if (!interactive()) q()
}))

PS:您可能不希望警告= 2(警告转换为错误)

答案 1 :(得分:10)

我最终编写了一个通用记录器,当标准R&#34;消息&#34;,&#34;警告&#34;时,它会产生类似Java的记录消息。并且&#34;停止&#34;方法被称为。它包括时间戳,警告及以上的堆栈跟踪。

非常感谢Man Group允许分发此内容!还要感谢鲍勃·奥尔布赖特,他的回答让我对我正在寻找的东西有所帮助。

withJavaLogging = function(expr, silentSuccess=FALSE, stopIsFatal=TRUE) {
    hasFailed = FALSE
    messages = list()
    warnings = list()
    logger = function(obj) {
        # Change behaviour based on type of message
        level = sapply(class(obj), switch, debug="DEBUG", message="INFO", warning="WARN", caughtError = "ERROR",
                error=if (stopIsFatal) "FATAL" else "ERROR", "")
        level = c(level[level != ""], "ERROR")[1]
        simpleMessage = switch(level, DEBUG=,INFO=TRUE, FALSE)
        quashable = switch(level, DEBUG=,INFO=,WARN=TRUE, FALSE)

        # Format message
        time  = format(Sys.time(), "%Y-%m-%d %H:%M:%OS3")
        txt   = conditionMessage(obj)
        if (!simpleMessage) txt = paste(txt, "\n", sep="")
        msg = paste(time, level, txt, sep=" ")
        calls = sys.calls()
        calls = calls[1:length(calls)-1]
        trace = limitedLabels(c(calls, attr(obj, "calls")))
        if (!simpleMessage && length(trace) > 0) {
            trace = trace[length(trace):1]
            msg = paste(msg, "  ", paste("at", trace, collapse="\n  "), "\n", sep="")
        }

        # Output message
        if (silentSuccess && !hasFailed && quashable) {
            messages <<- append(messages, msg)
            if (level == "WARN") warnings <<- append(warnings, msg)
        } else {
            if (silentSuccess && !hasFailed) {
                cat(paste(messages, collapse=""))
                hasFailed <<- TRUE
            }
            cat(msg)
        }

        # Muffle any redundant output of the same message
        optionalRestart = function(r) { res = findRestart(r); if (!is.null(res)) invokeRestart(res) }
        optionalRestart("muffleMessage")
        optionalRestart("muffleWarning")
    }
    vexpr = withCallingHandlers(withVisible(expr),
            debug=logger, message=logger, warning=logger, caughtError=logger, error=logger)
    if (silentSuccess && !hasFailed) {
        cat(paste(warnings, collapse=""))
    }
    if (vexpr$visible) vexpr$value else invisible(vexpr$value)
}

要使用它,只需将其包裹在代码中:

withJavaLogging({
  // Your code here...
})

对于没有错误的更安静的输出(对测试很有用!),设置silentSuccess标志。只有在发生错误时才会输出消息,以便为失败提供上下文。

要实现原始目标(转储堆栈跟踪+继续),只需使用try:

try(withJavaLogging({
  // Your code here...
}, stopIsFatal=FALSE))

答案 2 :(得分:8)

如果对选项(错误...)触发的内容感兴趣,您也可以这样做:

options(error=traceback)

据我所知,它完成了Bob建议的解决方案所做的大部分工作,但具有更短的优势。

(根据需要随意与keep.source = TRUE,warn = 2等结合使用。)

答案 3 :(得分:5)

你试过

吗?
 options(error=recover)

设置?钱伯斯的“数据分析软件”对调试有一些有用的提示。

答案 4 :(得分:1)

没有行号,但这是我到目前为止最接近的行号:

run = function() {
    // Your code here...
}
withCallingHandlers(run(), error=function(e)cat(conditionMessage(e), sapply(sys.calls(),function(sc)deparse(sc)[1]), sep="\n   ")) 

答案 5 :(得分:0)

我认为您需要使用tryCatch()。您可以在tryCatch()函数中执行任何操作,因此我不清楚为什么您将此视为复杂。也许发布您的代码示例?

答案 6 :(得分:0)

这是@ chrispy上面回答的后续内容,他提出了withJavaLogging函数。我评论说他的解决方案是鼓舞人心的,但对我来说,在堆栈跟踪开始时我不希望看到的一些输出损坏了。

为了说明,请考虑以下代码:

f1 = function() {
        # line #2 of the function definition; add this line to confirm that the stack trace line number for this function is line #3 below
        catA("f2 = ", f2(), "\n", sep = "")
    }

    f2 = function() {
        # line #2 of the function definition; add this line to confirm that the stack trace line number for this function is line #4 below
        # line #3 of the function definition; add this line to confirm that the stack trace line number for this function is line #4 below
        stop("f2 always causes an error for testing purposes")
    }

如果我执行第withJavaLogging( f1() )行,我会得到输出

2017-02-17 17:58:29.556 FATAL f2 always causes an error for testing purposes
      at .handleSimpleError(function (obj) 
    {
        level = sapply(class(obj), switch, debug = "DEBUG", message = "INFO", warning = "WARN", caughtError = "ERROR", error = if (stopIsFatal) 
            "FATAL"
        else "ERROR", "")
        level = c(level[level != ""], "ERROR")[1]
        simpleMessage = switch(level, DEBUG = , INFO = TRUE
      at #4: stop("f2 always causes an error for testing purposes")
      at f2()
      at catA.R#8: cat(...)
      at #3: catA("f2 = ", f2(), "\n", sep = "")
      at f1()
      at withVisible(expr)
      at #43: withCallingHandlers(withVisible(expr), debug = logger, message = logger, warning = logger, caughtError = logger, error = logger)
      at withJavaLogging(f1())
    Error in f2() : f2 always causes an error for testing purposes

我不希望看到at .handleSimpleError(function (obj)行后跟withJavaLogging函数中定义的记录器函数的源代码。我在上面评论过,我可以通过将trace = trace[length(trace):1]更改为trace = trace[(length(trace) - 1):1]

来抑制不需要的输出

为了方便其他人阅读本文,这里是我现在使用的函数的完整版本(从withJavaLogging重命名为logFully,并稍微重新格式化以符合我的可读性偏好):

logFully = function(expr, silentSuccess = FALSE, stopIsFatal = TRUE) {
    hasFailed = FALSE
    messages = list()
    warnings = list()

    logger = function(obj) {
        # Change behaviour based on type of message
        level = sapply(
            class(obj),
            switch,
            debug = "DEBUG",
            message = "INFO",
            warning = "WARN",
            caughtError = "ERROR",
            error = if (stopIsFatal) "FATAL" else "ERROR",
            ""
        )
        level = c(level[level != ""], "ERROR")[1]
        simpleMessage = switch(level, DEBUG = TRUE, INFO = TRUE, FALSE)
        quashable = switch(level, DEBUG = TRUE, INFO = TRUE, WARN = TRUE, FALSE)

        # Format message
        time = format(Sys.time(), "%Y-%m-%d %H:%M:%OS3")
        txt = conditionMessage(obj)
        if (!simpleMessage) txt = paste(txt, "\n", sep = "")
        msg = paste(time, level, txt, sep = " ")
        calls = sys.calls()
        calls = calls[1:length(calls) - 1]
        trace = limitedLabels(c(calls, attr(obj, "calls")))
        if (!simpleMessage && length(trace) > 0) {
            trace = trace[(length(trace) - 1):1]
            msg = paste(msg, "  ", paste("at", trace, collapse = "\n  "), "\n", sep = "")
        }

        # Output message
        if (silentSuccess && !hasFailed && quashable) {
            messages <<- append(messages, msg)
            if (level == "WARN") warnings <<- append(warnings, msg)
        } else {
            if (silentSuccess && !hasFailed) {
                cat(paste(messages, collapse = ""))
                hasFailed <<- TRUE
            }
            cat(msg)
        }

        # Muffle any redundant output of the same message
        optionalRestart = function(r) { res = findRestart(r); if (!is.null(res)) invokeRestart(res) }
        optionalRestart("muffleMessage")
        optionalRestart("muffleWarning")
    }

    vexpr = withCallingHandlers( withVisible(expr), debug = logger, message = logger, warning = logger, caughtError = logger, error = logger )

    if (silentSuccess && !hasFailed) {
        cat(paste(warnings, collapse = ""))
    }

    if (vexpr$visible) vexpr$value else invisible(vexpr$value)
}

如果我执行第logFully( f1() )行,我会得到我想要的输出,这只是

2017-02-17 18:05:05.778 FATAL f2 always causes an error for testing purposes
  at #4: stop("f2 always causes an error for testing purposes")
  at f2()
  at catA.R#8: cat(...)
  at #3: catA("f2 = ", f2(), "\n", sep = "")
  at f1()
  at withVisible(expr)
  at logFully.R#110: withCallingHandlers(withVisible(expr), debug = logger, message = logger, warning = logger, caughtError = logger, error = logger)
  at logFully(f1())
Error in f2() : f2 always causes an error for testing purposes

答案 7 :(得分:-1)

我编写了一个类似于try的解决方案,除了它还返回调用堆栈。

tryStack <- function(
expr,
silent=FALSE
)
{
tryenv <- new.env()
out <- try(withCallingHandlers(expr, error=function(e)
  {
  stack <- sys.calls()
  stack <- stack[-(2:7)]
  stack <- head(stack, -2)
  stack <- sapply(stack, deparse)
  if(!silent && isTRUE(getOption("show.error.messages"))) 
    cat("This is the error stack: ", stack, sep="\n")
  assign("stackmsg", value=paste(stack,collapse="\n"), envir=tryenv)
  }), silent=silent)
if(inherits(out, "try-error")) out[2] <- tryenv$stackmsg
out
}

lower <- function(a) a+10
upper <- function(b) {plot(b, main=b) ; lower(b) }

d <- tryStack(upper(4))
d <- tryStack(upper("4"))
cat(d[2])

我的答案中有更多信息: https://stackoverflow.com/a/40899766/1587132