Skip to content

Instantly share code, notes, and snippets.

@krlmlr
Created August 6, 2023 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krlmlr/1ce726fa6ebb48eb78b2c548b546e99e to your computer and use it in GitHub Desktop.
Save krlmlr/1ce726fa6ebb48eb78b2c548b546e99e to your computer and use it in GitHub Desktop.
Call logging
# Use: add `log_call("<function name")` to your functions
# TODO: Add to all functions in a namespace via `trace()`
indent <- new_environment(list(value = 0L))
log_call <- function(name, call = sys.call(-1), envir = parent.frame()) {
srcref <- attr(call, "srcref")
if (is.null(srcref)) {
call_dep <- paste(gsub("^ +", "", deparse(call)), collapse = "")
file_line <- ""
} else {
call_dep <- paste(gsub("^ +", "", as.charactfer(srcref)), collapse = "")
filename <- attr(srcref, "srcfile")$filename
if (identical(filename, "")) {
filename <- "<unknown>"
} else {
filename <- basename(filename)
}
filename <- cli::format_inline("{.file {filename}:{srcref[[1]]}:{srcref[[2]]}}")
file_line <- paste0(" (", filename, ")")
}
indent_str <- strrep(" ", indent$value)
log <- paste0(name, "(): ", call_dep, file_line)
writeLines(paste0(indent_str, "+", log))
indent$value <- indent$value + 1L
withr::defer(envir = envir, {
indent$value <- indent$value - 1L
writeLines(paste0(indent_str, "-", log))
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment