glog_asio_sink.h
1 // Copyright 2018, Beeri 15. All rights reserved.
2 // Author: Roman Gershman (romange@gmail.com)
3 //
4 
5 #pragma once
6 
7 #include <glog/logging.h>
8 #include <boost/fiber/buffered_channel.hpp>
9 
10 #include "util/asio/io_context.h"
11 #include "util/fibers/event_count.h"
12 
13 namespace util {
14 
15 class GlogAsioSink : public IoContext::Cancellable, ::google::LogSink {
16  public:
17  GlogAsioSink();
18  ~GlogAsioSink() noexcept;
19 
20  void Run() override;
21  void Cancel() override;
22 
23  void WaitTillRun();
24 
25  protected:
26  struct Item {
27  const char* full_filename;
28  const char* base_filename;
29  google::LogSeverity severity;
30  int line;
31  struct ::tm tm_time;
32  std::string message; // Can cause performance penalty.
33  };
34  ::boost::fibers::buffered_channel<Item> msg_q_;
35 
36  unsigned lost_messages_ = 0;
37 
38  virtual bool ShouldIgnore(google::LogSeverity severity, const char* full_filename, int line) {
39  return false;
40  }
41 
42  // Is called from Run loop. Should not block the thread.
43  virtual void HandleItem(const Item& item) = 0;
44 
45  private:
47  void send(google::LogSeverity severity, const char* full_filename, const char* base_filename,
48  int line, const struct ::tm* tm_time, const char* message, size_t message_len) override;
49 
50  void WaitTillSent() override;
51 
52  std::atomic_bool run_started_{false};
53  fibers_ext::EventCount ec_;
54 };
55 
56 } // namespace util