Track functions name, when started and when finished

Viewed 37

I am trying to track name, start and end of a function. That is, when a function execute, I try to get the name of the function, when start and when finished. I use two functions, "on.exit()" and "match.call()". They are work perfectly.

abcde<-function(){
  cat(paste("\n function started:",match.call(),"\n ",Sys.time(),"\n"))
  on.exit({
    cat(paste("\n function finished:",match.call(),"\n ",Sys.time(),"\n"))
   })
  Sys.sleep(2)
}
abcde()

I am trying to make a function to do this(since I have too many functions):

mf_on_exit_start<-function(match_call=match.call()){
  cat(paste("\n function started:",match_call,"\n ",Sys.time(),"\n"))
  on.exit({
    cat(paste("\n function finished:",match_call,"\n ",Sys.time(),"\n"))
  })
}
abcdef<-function(){
  mf_on_exit_start(match.call())
  Sys.sleep(2)
}
abcdef()  

But unfortunately the function does not work!

1 Answers

Your approach would need your mf_on_exit_start to set on.exit within its caller (i.e. in abcdef()), but that's not possible. on.exit always applies in the current function only.

To do what you want, you'll need to reorganize things, so that the on.exit happens in the caller of abcdef(). For example,

with_mf <- function(expr) {
  call <- deparse(substitute(expr))
  cat(paste("\n function started:",call,"\n ",Sys.time(),"\n"))
  on.exit({
    cat(paste("\n function finished:",call,"\n ",Sys.time(),"\n"))
  })
  expr
}

abcdef<-function(){
  Sys.sleep(2)
}

with_mf(abcdef())
#> 
#>  function started: abcdef() 
#>   2022-07-16 05:07:27 
#> 
#>  function finished: abcdef() 
#>   2022-07-16 05:07:29

Created on 2022-07-16 by the reprex package (v2.0.1)

Related