callbackSink.hpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2020-2021, NVIDIA CORPORATION.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #pragma once
17 
18 #include <iostream>
19 #include <mutex>
20 
21 #define SPDLOG_HEADER_ONLY
22 #include <spdlog/common.h>
23 #include <spdlog/details/log_msg.h>
24 #include <spdlog/sinks/base_sink.h>
25 
26 namespace spdlog {
27 namespace sinks {
28 
29 typedef void (*LogCallback)(int lvl, const char* msg);
30 
31 template <class Mutex>
32 class CallbackSink : public base_sink<Mutex> {
33  public:
34  explicit CallbackSink(std::string tag = "spdlog",
35  LogCallback callback = nullptr,
36  void (*flush)() = nullptr)
37  : _callback{callback}, _flush{flush} {};
38 
39  void set_callback(LogCallback callback) { _callback = callback; }
40  void set_flush(void (*flush)()) { _flush = flush; }
41 
42  protected:
43  void sink_it_(const details::log_msg& msg) override
44  {
45  spdlog::memory_buf_t formatted;
46  base_sink<Mutex>::formatter_->format(msg, formatted);
47  std::string msg_string = fmt::to_string(formatted);
48 
49  if (_callback) {
50  _callback(static_cast<int>(msg.level), msg_string.c_str());
51  } else {
52  std::cout << msg_string;
53  }
54  }
55 
56  void flush_() override
57  {
58  if (_flush) {
59  _flush();
60  } else {
61  std::cout << std::flush;
62  }
63  }
64 
66  void (*_flush)();
67 };
68 
71 
72 } // end namespace sinks
73 } // end namespace spdlog
Definition: callbackSink.hpp:32
void sink_it_(const details::log_msg &msg) override
Definition: callbackSink.hpp:43
void set_callback(LogCallback callback)
Definition: callbackSink.hpp:39
LogCallback _callback
Definition: callbackSink.hpp:65
CallbackSink(std::string tag="spdlog", LogCallback callback=nullptr, void(*flush)()=nullptr)
Definition: callbackSink.hpp:34
void(* _flush)()
Definition: callbackSink.hpp:66
void flush_() override
Definition: callbackSink.hpp:56
void set_flush(void(*flush)())
Definition: callbackSink.hpp:40
void(* LogCallback)(int lvl, const char *msg)
Definition: callbackSink.hpp:29
Definition: callbackSink.hpp:26