16 #ifndef TENSORFLOW_SERVING_CORE_REQUEST_LOGGER_H_
17 #define TENSORFLOW_SERVING_CORE_REQUEST_LOGGER_H_
22 #include "google/protobuf/message.h"
23 #include "tensorflow/core/lib/core/status.h"
24 #include "tensorflow_serving/apis/logging.pb.h"
25 #include "tensorflow_serving/config/logging_config.pb.h"
26 #include "tensorflow_serving/core/log_collector.h"
27 #include "tensorflow_serving/core/stream_logger.h"
29 namespace tensorflow {
36 class RequestLogger :
public std::enable_shared_from_this<RequestLogger> {
39 const std::vector<string>& saved_model_tags,
40 std::unique_ptr<LogCollector> log_collector);
46 Status Log(
const google::protobuf::Message& request,
const google::protobuf::Message& response,
47 const LogMetadata& log_metadata);
52 template <
typename Request,
typename Response>
53 using GetStreamLoggerFn = std::function<StreamLogger<Request, Response>*()>;
54 template <
typename Request,
typename Response>
55 void MaybeStartLoggingStream(
56 const LogMetadata& log_metadata,
57 GetStreamLoggerFn<Request, Response> get_stream_logger_fn);
59 const LoggingConfig& logging_config()
const {
return logging_config_; }
65 virtual Status CreateLogMessage(
const google::protobuf::Message& request,
66 const google::protobuf::Message& response,
67 const LogMetadata& log_metadata,
68 std::unique_ptr<google::protobuf::Message>* log) = 0;
71 virtual LogMetadata FillLogMetadata(
const LogMetadata& lm_in) = 0;
74 Status Log(
const google::protobuf::Message& log);
77 class UniformSampler {
79 UniformSampler() : rd_(), gen_(rd_()), dist_(0, 1) {}
83 bool Sample(
const double rate) {
return dist_(gen_) < rate; }
86 std::random_device rd_;
88 std::uniform_real_distribution<double> dist_;
91 const LoggingConfig logging_config_;
92 const std::vector<string> saved_model_tags_;
93 std::unique_ptr<LogCollector> log_collector_;
94 UniformSampler uniform_sampler_;
98 template <
typename Request,
typename Response>
99 void RequestLogger::MaybeStartLoggingStream(
100 const LogMetadata& log_metadata,
101 GetStreamLoggerFn<Request, Response> get_stream_logger_fn) {
105 if (!uniform_sampler_.Sample(
106 logging_config_.sampling_config().sampling_rate())) {
110 auto* stream_logger = get_stream_logger_fn();
111 if (stream_logger ==
nullptr)
return;
113 LogMetadata lm_out = FillLogMetadata(log_metadata);
114 std::weak_ptr<RequestLogger> logger_ref(shared_from_this());
115 stream_logger->AddLogCallback(
116 lm_out, [logger_ref = std::move(logger_ref)](
const google::protobuf::Message& log) {
120 if (
auto logger = logger_ref.lock(); logger !=
nullptr) {
121 TF_RETURN_IF_ERROR(logger->Log(log));