0

I have a requirement to output a time stamped log of APIs in real time. These have to be output on the R console.

I wrote this function as I read a SO question here to be called from inside the API end point function. But this outputs the function name "print_log" itself. And when I replace -1 with -2, I get the full code of the calling function but without the name of the function. All I need is the function name that calls print_log.

  print_log<-function(){
  api<-deparse(sys.calls()[[sys.nframe()-1]])
  sprintf("%20s:%40s",now(),api)
  }
Lazarus Thurston
  • 1,197
  • 15
  • 33

1 Answers1

0

I'm not sure off the top of my head how to rectify the code as you have it, but a couple of other alternatives:

  1. You could front Plumber with a proxy that handles logging of requests. See an example here.
  2. You could use a plumber filter which gets executed before any endpoint processes the request.

.

#' @filter log
function(req){
   cat("Incoming request for", req$PATH_INFO, "\n")
   forward()
}

#' @get /
function(){
   # ...
}

If you want to include the parameters that were provided in the request, you can just have your filter accept ....

#' @filter logger
function(...){
  print(list(...))
  forward()
}

For a request like server.org/endpoint?a=1&b=2, That will print out something like:

$res
<PlumberResponse>
  Public:
  body: NULL
clone: function (deep = FALSE) 
  headers: list
initialize: function (serializer = serializer_json()) 
  serializer: function (val, req, res, errorHandler) 
    setCookie: function (name, value, path) 
      setHeader: function (name, value) 
        status: 200
toResponse: function () 

$req
<environment: 0x108fbdff0>

$a
[1] "1"

$b
[1] "2"
Jeff Allen
  • 17,277
  • 8
  • 49
  • 70
  • Great idea @Jeff. I could have used it if it allowed a little more flexibility in logging the API details... I need not just the name of the function but the parameters passed in. Do you think that is possible? – Lazarus Thurston Jul 20 '17 at 05:30
  • Jeff, do we have an option to extract a log with parameter names & values as well? – Lazarus Thurston Jul 21 '17 at 09:23
  • Edited to include that answer. – Jeff Allen Jul 24 '17 at 14:13
  • Thanks @Jeff. The list(...) actually dumps everything in a list format in multiple lines and this is not suitable for logging. What I need is a log. Something like `print(paste0(...))` but this does not work. – Lazarus Thurston Jul 28 '17 at 17:25