如何设置使用RestRserve
将每个请求记录到不同的 json 文件中?
我尝试使用lgr
包(在 RestRserve 关于日志记录的文档中提到(,如下所示:
library(RestRserve)
library(lgr)
app = Application$new(content_type = "text/plain")
# RestRserve logger
app$logger = RestRserve::Logger$new(level = "trace", name = "mylogger",
printer=function(timestamp, level, logger_name, pid, message, ...)
{
lgr$log(level=tolower(level), msg=message, ...)
}
)
# JSON appender in lgr
tf <- tempfile(tmpdir="D:/temp", fileext=".log")
lgr$add_appender(AppenderJson$new(tf), name = "json")
# Endpoint
app$add_get("/sqrt", function(request, response) {
on.exit({
# Next log file
tf <- tempfile(tmpdir="D:/temp", fileext=".log")
lgr$appenders$json$set_file(tf)
})
app$logger$info(msg="", context=list(request_id = request$id, message="Process start"))
response$body = sqrt(x)
app$logger$info(msg="", context=list(request_id = request$id, message="Process end"))
})
# Submit request
request = Request$new(path = "/sqrt", method = "GET", parameters_query = list(x = "10"))
response = app$process_request(request)
但这会将请求的日志信息拆分到两个文件中。我也非常确定它不适用于同时请求。
我相信你甚至不需要任何特殊的记录器 - 只需使用writeLines
.您也可以依靠req$id
来命名文件,因为它是唯一的。
library(RestRserve)
req = Request$new()
res = Response$new()
fl = file.path(tempdir(), paste0(req$id, ".log"))
con = file(fl, open = "at")
writeLines("Process start", con)
res$set_body(sqrt(10))
writeLines("Process end", con)
close(con)
readLines(fl)
unlink(fl)