Skip to content

Commit

Permalink
Add knitr hook
Browse files Browse the repository at this point in the history
  • Loading branch information
thomasp85 committed Jan 28, 2025
1 parent f29cdea commit 01a3d90
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export(layout_logging)
export(layout_simple)
export(layout_syslognet)
export(log_appender)
export(log_chunk_time)
export(log_debug)
export(log_elapsed)
export(log_elapsed_start)
Expand Down
37 changes: 37 additions & 0 deletions R/helpers.R
Original file line number Diff line number Diff line change
Expand Up @@ -300,3 +300,40 @@ log_failure <- function(expression) {
}
)
}

#' Automatically log execution time of knitr chunks
#'
#' Calling this function in the first chunk of a document will instruct knitr
#' to automatically log the execution time of each chunk. If using
#' [formatter_glue()] or [formatter_cli()] then the `options` variable will be
#' available, providing the chunk options such as chunk label etc.
#'
#' @inheritParams log_elapsed
#'
#' @export
#'
#' @examples
#' # To be put in the first chunk of a document
#' log_chunk_time("chunk {options$label}")
#'
log_chunk_time <- function(..., level = INFO, namespace = NA_character_) {
if (!requireNamespace("knitr", quietly = TRUE)) {
stop("knitr is required to use this functionality", call. = FALSE)
}
if (!isTRUE(getOption("knitr.in.progress"))) {
return(invisible())
}
args <- list(...)
args$level <- level
args$namespace <- namespace
knitr::knit_hooks$set(logger_timer = function(before, options) {
if (before) {
log_elapsed_start(namespace = namespace, quiet = TRUE)
} else {
do.call(log_elapsed, args)
}
})
knitr::opts_chunk$set(logger_timer = TRUE)

invisible()
}
26 changes: 26 additions & 0 deletions man/log_chunk_time.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 01a3d90

Please sign in to comment.