Add logs in a R Plumber Api

Viewed 220

I'm creating some APIs with R and Plumber. I configure the entrypoint.R like that

library(plumber)
library(logger)

# Create Log directory
log_dir <- "/api/logs"
if (!fs::dir_exists(log_dir)) fs::dir_create(log_dir)
log_appender(appender_tee(tempfile("plumber_", log_dir, ".log")))

convert_empty <- function(string) {
  if (string == "") {
    "-"
  } else {
    string
  }
}

# Initiate
# pr <- plumber::plumb(here::here('plumber.R')) # local test
pr <- plumber::plumb(rev(commandArgs())[1]) # via Docker


args <- list(host = '0.0.0.0', port = 8000)
if (packageVersion('plumber') >= '1.0.0') { pr$setDocs(TRUE) } else { args$swagger <- TRUE }


# Create log hook
pr$registerHooks(
  list(
    preroute = function() {
      # Start timer for log info
      tictoc::tic()
    },
    postroute = function(req, res) {
      end <- tictoc::toc(quiet = TRUE)
      # Log details about the request and the response
      # log_info('{convert_empty(req$REMOTE_ADDR)} "{convert_empty(req$HTTP_USER_AGENT)}" {convert_empty(req$HTTP_HOST)} {convert_empty(req$REQUEST_METHOD)} {convert_empty(req$PATH_INFO)} {convert_empty(res$status)} {round(end$toc - end$tic, digits = getOption("digits", 5))}')
      log_info('{convert_empty(req$REMOTE_ADDR)}')
    }
  )
)

# Run entrypoint
do.call(pr$run, args)

I can't have the full logs because this line

log_info('{convert_empty(req$REMOTE_ADDR)} "{convert_empty(req$HTTP_USER_AGENT)}" {convert_empty(req$HTTP_HOST)} {convert_empty(req$REQUEST_METHOD)} {convert_empty(req$PATH_INFO)} {convert_empty(res$status)} {round(end$toc - end$tic, digits = getOption("digits", 5))}')

creates an error and the application stops to work.

Also, I want to add my custom logs in the API to track the flow for debug purposes. For example in the api

#* Ping
#* @get /ping
function() {
    rtn <- jsonlite::unbox(data.frame(Status = TRUE))
    return(rtn)
}

I want to add my log so I can check what functions are calling and what is happening in them.

1 Answers

I found a library called Log4R that allows me to add logs from my functions and save them on a file. Same examples here.

Install the package

install.packages("log4r")

Use the package

logger <- logger()

info(logger, "Located nearest gas station.")
#> INFO  [2019-09-04 16:31:04] Located nearest gas station.
warn(logger, "Ez-Gas sensor network is not available.")
#> WARN  [2019-09-04 16:31:04] Ez-Gas sensor network is not available.
debug(logger, "Debug messages are suppressed by default.")
Related