logging.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2013-2024 Regents of the University of California.
4  *
5  * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
6  *
7  * ndn-cxx library is free software: you can redistribute it and/or modify it under the
8  * terms of the GNU Lesser General Public License as published by the Free Software
9  * Foundation, either version 3 of the License, or (at your option) any later version.
10  *
11  * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
12  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
13  * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
14  *
15  * You should have received copies of the GNU General Public License and GNU Lesser
16  * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
17  * <http://www.gnu.org/licenses/>.
18  *
19  * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
20  */
21 
22 #include "ndn-cxx/util/logging.hpp"
23 #include "ndn-cxx/util/logger.hpp"
24 #include "ndn-cxx/util/time.hpp"
25 
26 #ifdef __ANDROID__
27 #include "ndn-cxx/util/impl/logger-android.hpp"
28 #endif
29 
30 #include <boost/log/attributes/function.hpp>
31 #include <boost/log/expressions.hpp>
32 #include <boost/log/expressions/attr.hpp>
33 #include <boost/log/expressions/formatters/date_time.hpp>
34 #include <boost/log/support/date_time.hpp>
35 #include <boost/range/adaptor/map.hpp>
36 #include <boost/range/algorithm/copy.hpp>
37 #include <boost/range/iterator_range.hpp>
38 
39 #include <cinttypes> // for PRIdLEAST64
40 #include <cstdio> // for std::snprintf()
41 #include <cstdlib> // for std::abs()
42 #include <iostream>
43 #include <sstream>
44 
45 namespace ndn::util {
46 namespace log {
47 
48 static std::string
49 makeTimestamp()
50 {
51  using namespace ndn::time;
52 
53  const auto sinceEpoch = system_clock::now().time_since_epoch();
54  BOOST_ASSERT(sinceEpoch.count() >= 0);
55  // use abs() to silence truncation warning in snprintf(), see #4365
56  const auto usecs = std::abs(duration_cast<microseconds>(sinceEpoch).count());
57  const auto usecsPerSec = microseconds::period::den;
58 
59  // 10 (whole seconds) + '.' + 6 (fraction) + '\0'
60  std::string buffer(10 + 1 + 6 + 1, '\0'); // note 1 extra byte still needed for snprintf
61  BOOST_ASSERT_MSG(usecs / usecsPerSec <= 9999999999, "whole seconds cannot fit in 10 characters");
62 
63  static_assert(std::is_same_v<microseconds::rep, int_least64_t>,
64  "PRIdLEAST64 is incompatible with microseconds::rep");
65  std::snprintf(&buffer.front(), buffer.size(), "%" PRIdLEAST64 ".%06" PRIdLEAST64,
66  usecs / usecsPerSec, usecs % usecsPerSec);
67 
68  // need to remove extra 1 byte ('\0')
69  buffer.pop_back();
70  return buffer;
71 }
72 
73 BOOST_LOG_ATTRIBUTE_KEYWORD(timestamp, "Timestamp", std::string)
74 
75 } // namespace log
76 
78 
79 Logging&
80 Logging::get()
81 {
82  // Initialization of block-scope variables with static storage duration is thread-safe.
83  // See ISO C++ standard [stmt.dcl]/4
84  static Logging instance;
85  return instance;
86 }
87 
88 Logging::Logging()
89 {
90 #ifndef __ANDROID__
91  bool wantAutoFlush = std::getenv("NDN_LOG_NOFLUSH") == nullptr;
92  auto destination = makeDefaultStreamDestination(shared_ptr<std::ostream>(&std::clog, [] (auto&&) {}),
93  wantAutoFlush);
94 #else
95  auto destination = detail::makeAndroidLogger();
96 #endif // __ANDROID__
97 
98  // cannot call the static setDestination(), as the singleton object is not yet constructed
99  this->setDestinationImpl(std::move(destination));
100 
101  const char* env = std::getenv("NDN_LOG");
102  if (env != nullptr) {
103  this->setLevelImpl(env);
104  }
105 
106  boost::log::core::get()->add_global_attribute("Timestamp",
107  boost::log::attributes::make_function(&log::makeTimestamp));
108 }
109 
110 void
111 Logging::addLoggerImpl(Logger& logger)
112 {
113  std::lock_guard<std::mutex> lock(m_mutex);
114 
115  const std::string& moduleName = logger.getModuleName();
116  m_loggers.emplace(moduleName, &logger);
117 
118  logger.setLevel(findLevel(moduleName));
119 }
120 
121 void
122 Logging::registerLoggerNameImpl(std::string name)
123 {
124  std::lock_guard<std::mutex> lock(m_mutex);
125  m_loggers.emplace(std::move(name), nullptr);
126 }
127 
128 std::set<std::string>
129 Logging::getLoggerNamesImpl() const
130 {
131  std::lock_guard<std::mutex> lock(m_mutex);
132 
133  std::set<std::string> loggerNames;
134  boost::copy(m_loggers | boost::adaptors::map_keys, std::inserter(loggerNames, loggerNames.end()));
135  return loggerNames;
136 }
137 
138 LogLevel
139 Logging::findLevel(std::string mn) const
140 {
141  while (!mn.empty()) {
142  if (auto it = m_enabledLevel.find(mn); it != m_enabledLevel.end()) {
143  return it->second;
144  }
145  size_t pos = mn.find_last_of('.');
146  if (pos < mn.size() - 1) {
147  mn = mn.substr(0, pos + 1);
148  }
149  else if (pos == mn.size() - 1) {
150  mn.pop_back();
151  pos = mn.find_last_of('.');
152  if (pos != std::string::npos) {
153  mn = mn.substr(0, pos + 1);
154  }
155  else {
156  mn = "";
157  }
158  }
159  else {
160  mn = "";
161  }
162  }
163 
164  auto it = m_enabledLevel.find(mn);
165  return it != m_enabledLevel.end() ? it->second : INITIAL_DEFAULT_LEVEL;
166 }
167 
168 #ifdef NDN_CXX_WITH_TESTS
169 bool
170 Logging::removeLogger(Logger& logger)
171 {
172  const std::string& moduleName = logger.getModuleName();
173  auto range = m_loggers.equal_range(moduleName);
174  for (auto i = range.first; i != range.second; ++i) {
175  if (i->second == &logger) {
176  m_loggers.erase(i);
177  return true;
178  }
179  }
180  return false;
181 }
182 #endif // NDN_CXX_WITH_TESTS
183 
184 void
185 Logging::setLevelImpl(const std::string& prefix, LogLevel level)
186 {
187  std::lock_guard<std::mutex> lock(m_mutex);
188 
189  if (prefix.empty() || prefix.back() == '*') {
190  std::string p = prefix;
191  if (!p.empty()) {
192  p.pop_back();
193  }
194 
195  for (auto i = m_enabledLevel.begin(); i != m_enabledLevel.end();) {
196  if (i->first.compare(0, p.size(), p) == 0) {
197  i = m_enabledLevel.erase(i);
198  }
199  else {
200  ++i;
201  }
202  }
203  m_enabledLevel[p] = level;
204 
205  for (const auto& pair : m_loggers) {
206  if (pair.first.compare(0, p.size(), p) == 0 && pair.second != nullptr) {
207  pair.second->setLevel(level);
208  }
209  }
210  }
211  else {
212  m_enabledLevel[prefix] = level;
213  auto range = boost::make_iterator_range(m_loggers.equal_range(prefix));
214  for (const auto& pair : range) {
215  if (pair.second != nullptr) {
216  pair.second->setLevel(level);
217  }
218  }
219  }
220 }
221 
222 void
223 Logging::setLevelImpl(const std::string& config)
224 {
225  std::stringstream ss(config);
226  std::string configModule;
227  while (std::getline(ss, configModule, ':')) {
228  size_t ind = configModule.find('=');
229  if (ind == std::string::npos) {
230  NDN_THROW(std::invalid_argument("malformed logging config: '=' is missing"));
231  }
232 
233  std::string moduleName = configModule.substr(0, ind);
234  LogLevel level = parseLogLevel(configModule.substr(ind + 1));
235  this->setLevelImpl(moduleName, level);
236  }
237 }
238 
239 #ifdef NDN_CXX_WITH_TESTS
240 void
241 Logging::resetLevels()
242 {
243  this->setLevelImpl("*", INITIAL_DEFAULT_LEVEL);
244  m_enabledLevel.clear();
245 }
246 #endif // NDN_CXX_WITH_TESTS
247 
248 void
249 Logging::setDestination(std::ostream& os, bool wantAutoFlush)
250 {
251  auto destination = makeDefaultStreamDestination(shared_ptr<std::ostream>(&os, [] (auto&&) {}),
252  wantAutoFlush);
253  setDestination(std::move(destination));
254 }
255 
256 class TextOstreamBackend : public boost::log::sinks::text_ostream_backend
257 {
258 public:
259  TextOstreamBackend(std::shared_ptr<std::ostream> os, bool wantAutoFlush)
260  : m_stdPtr(std::move(os))
261  {
262  auto_flush(wantAutoFlush);
263  add_stream(boost::shared_ptr<std::ostream>(m_stdPtr.get(), [] (auto&&) {}));
264  }
265 
266 private:
267  // Quite a mess right now because Boost.Log uses boost::shared_ptr and we are using
268  // std::shared_ptr. When it is finally fixed, we can remove this mess.
269  std::shared_ptr<std::ostream> m_stdPtr;
270 };
271 
272 boost::shared_ptr<boost::log::sinks::sink>
273 Logging::makeDefaultStreamDestination(shared_ptr<std::ostream> os, bool wantAutoFlush)
274 {
275  auto backend = boost::make_shared<TextOstreamBackend>(std::move(os), wantAutoFlush);
276  auto destination = boost::make_shared<boost::log::sinks::asynchronous_sink<TextOstreamBackend>>(backend);
277 
278  namespace expr = boost::log::expressions;
279  destination->set_formatter(expr::stream
280  << expr::attr<std::string>(log::timestamp.get_name())
281  << " " << std::setw(5) << expr::attr<LogLevel>(log::severity.get_name()) << ": "
282  << "[" << expr::attr<std::string>(log::module.get_name()) << "] "
283  << expr::smessage);
284  return destination;
285 }
286 
287 void
288 Logging::setDestinationImpl(boost::shared_ptr<boost::log::sinks::sink> destination)
289 {
290  std::lock_guard<std::mutex> lock(m_mutex);
291 
292  if (destination == m_destination) {
293  return;
294  }
295 
296  if (m_destination != nullptr) {
297  boost::log::core::get()->remove_sink(m_destination);
298  m_destination->flush();
299  }
300 
301  m_destination = std::move(destination);
302 
303  if (m_destination != nullptr) {
304  boost::log::core::get()->add_sink(m_destination);
305  }
306 }
307 
308 #ifdef NDN_CXX_WITH_TESTS
309 boost::shared_ptr<boost::log::sinks::sink>
310 Logging::getDestination() const
311 {
312  return m_destination;
313 }
314 
315 void
316 Logging::setLevelImpl(const std::unordered_map<std::string, LogLevel>& prefixRules)
317 {
318  resetLevels();
319  for (const auto& rule : prefixRules) {
320  setLevelImpl(rule.first, rule.second);
321  }
322 }
323 
324 const std::unordered_map<std::string, LogLevel>&
325 Logging::getLevels() const
326 {
327  return m_enabledLevel;
328 }
329 #endif // NDN_CXX_WITH_TESTS
330 
331 void
332 Logging::flushImpl()
333 {
334  std::lock_guard<std::mutex> lock(m_mutex);
335 
336  if (m_destination != nullptr) {
337  m_destination->flush();
338  }
339 }
340 
341 } // namespace ndn::util
Controls the logging facility.
Definition: logging.hpp:47
static void setDestination(boost::shared_ptr< boost::log::sinks::sink > destination)
Set or replace log destination.
Definition: logging.hpp:212
static boost::shared_ptr< boost::log::sinks::sink > makeDefaultStreamDestination(shared_ptr< std::ostream > os, bool wantAutoFlush=true)
Create stream log destination using default formatting.
Definition: logging.cpp:273
#define NDN_THROW(e)
Definition: exception.hpp:56
constexpr duration< Rep, Period > abs(duration< Rep, Period > d)
Returns the absolute value of the duration d.
Definition: time.hpp:63
LogLevel parseLogLevel(std::string_view s)
Parse LogLevel from a string.
Definition: logger.cpp:53
constexpr LogLevel INITIAL_DEFAULT_LEVEL
Definition: logging.cpp:77
LogLevel
Indicates the severity level of a log message.
Definition: logger.hpp:45
@ NONE
no messages