在 R 管道工中添加日志 Api

Add logs in a R Plumber Api

我正在用 RPlumber 创建一些 API。我这样配置 entrypoint.R

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)

我无法获得完整的日志,因为这一行

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))}')

创建错误并且应用程序停止工作。

此外,我想在 API 中添加我的自定义日志以跟踪流程以进行调试。例如在 api

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

我想添加我的日志,这样我就可以检查调用了哪些函数以及其中发生了什么。

我找到了一个名为 Log4R that allows me to add logs from my functions and save them on a file. Same examples here 的库。

安装包

install.packages("log4r")

使用包

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.")