bitz-server  2.0.1
syslog_sink.h
1 //
2 // Copyright(c) 2015 Gabi Melman.
3 // Distributed under the MIT License (http://opensource.org/licenses/MIT)
4 //
5 
6 #pragma once
7 
8 #include "../common.h"
9 
10 #ifdef SPDLOG_ENABLE_SYSLOG
11 
12 #include "../details/log_msg.h"
13 #include "sink.h"
14 
15 #include <array>
16 #include <string>
17 #include <syslog.h>
18 
19 namespace spdlog {
20 namespace sinks {
26 class syslog_sink : public sink
27 {
28 public:
29  //
30  syslog_sink(const std::string &ident = "", int syslog_option = 0, int syslog_facility = LOG_USER)
31  : _ident(ident)
32  {
33  _priorities[static_cast<size_t>(level::trace)] = LOG_DEBUG;
34  _priorities[static_cast<size_t>(level::debug)] = LOG_DEBUG;
35  _priorities[static_cast<size_t>(level::info)] = LOG_INFO;
36  _priorities[static_cast<size_t>(level::warn)] = LOG_WARNING;
37  _priorities[static_cast<size_t>(level::err)] = LOG_ERR;
38  _priorities[static_cast<size_t>(level::critical)] = LOG_CRIT;
39  _priorities[static_cast<size_t>(level::off)] = LOG_INFO;
40 
41  // set ident to be program name if empty
42  ::openlog(_ident.empty() ? nullptr : _ident.c_str(), syslog_option, syslog_facility);
43  }
44 
45  ~syslog_sink() override
46  {
47  ::closelog();
48  }
49 
50  syslog_sink(const syslog_sink &) = delete;
51  syslog_sink &operator=(const syslog_sink &) = delete;
52 
53  void log(const details::log_msg &msg) override
54  {
55  ::syslog(syslog_prio_from_level(msg), "%s", msg.raw.str().c_str());
56  }
57 
58  void flush() override {}
59 
60 private:
61  std::array<int, 7> _priorities;
62  // must store the ident because the man says openlog might use the pointer as is and not a string copy
63  const std::string _ident;
64 
65  //
66  // Simply maps spdlog's log level to syslog priority level.
67  //
68  int syslog_prio_from_level(const details::log_msg &msg) const
69  {
70  return _priorities[static_cast<size_t>(msg.level)];
71  }
72 };
73 } // namespace sinks
74 } // namespace spdlog
75 
76 #endif
Definition: async_logger.h:26