~macslow/nux/nux.fix-839476

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*-
/*
 * Copyright 2011 Inalogic® Inc.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License, as
 * published by the  Free Software Foundation; either version 2.1 or 3.0
 * of the License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranties of
 * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the applicable version of the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of both the GNU Lesser General Public
 * License along with this program. If not, see <http://www.gnu.org/licenses/>
 *
 * Authored by: Tim Penhey <tim.penhey@canonical.com>
 *
 */

#pragma warning(disable: 4996)  // 'std::_Copy_impl': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'
                                // 'std::_Equal1': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'

#include "NuxCore.h"
#include "Logger.h"
#include "LoggingWriter.h"

#if defined(NUX_OS_LINUX)
#include <execinfo.h>
#endif

#include <map>
#include <sstream>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <boost/utility.hpp>

namespace nux {
namespace logging {

namespace {
char const* str_level(Level severity);
}

class LoggerModule
{
public:
  LoggerModule(std::string const& module, LoggerModulePtr const& parent);

  std::string const& module() const;

  bool IsErrorEnabled() const;
  bool IsWarningEnabled() const;
  bool IsInfoEnabled() const;
  bool IsDebugEnabled() const;
  bool IsTraceEnabled() const;

  void SetLogLevel(Level level);
  Level GetLogLevel() const;
  Level GetEffectiveLogLevel() const;

private:
  std::string module_;
  Level level_;
  LoggerModulePtr parent_;
  // An attempt to make sure the writer is around for as long as the loggers.
  Writer& writer_;
};

class LoggerModules : boost::noncopyable
{
public:
  static LoggerModules& Instance();

  LoggerModulePtr const& GetModule(std::string const& module);

  void reset();
  std::string dump_logging_levels(std::string const& prefix);

private:
  LoggerModules();

private:
  typedef std::map<std::string, LoggerModulePtr> ModuleMap;
  ModuleMap modules_;
  LoggerModulePtr root_;
};


inline std::string const& LoggerModule::module() const
{
  return module_;
}

inline bool LoggerModule::IsErrorEnabled() const
{
  return GetEffectiveLogLevel() <= Error;
}

inline bool LoggerModule::IsWarningEnabled() const
{
  return GetEffectiveLogLevel() <= Warning;
}

inline bool LoggerModule::IsInfoEnabled() const
{
  return GetEffectiveLogLevel() <= Info;
}

inline bool LoggerModule::IsDebugEnabled() const
{
  return GetEffectiveLogLevel() <= Debug;
}

inline bool LoggerModule::IsTraceEnabled() const
{
  return GetEffectiveLogLevel() <= Trace;
}

inline void LoggerModule::SetLogLevel(Level level)
{
  // The root module can't be unspecified.
  if (module_ == "" && level == NotSpecified)
    level = Warning;
  level_ = level;
}

inline Level LoggerModule::GetLogLevel() const
{
  return level_;
}

inline Level LoggerModule::GetEffectiveLogLevel() const
{
  if (level_ == NotSpecified && parent_)
    return parent_->GetEffectiveLogLevel();
  else
    return level_;
}


Logger::Logger(std::string const& module)
  : pimpl(LoggerModules::Instance().GetModule(module))
{
}

std::string const& Logger::module() const
{
  return pimpl->module();
}

bool Logger::IsErrorEnabled() const
{
  return pimpl->IsErrorEnabled();
}

bool Logger::IsWarningEnabled() const
{
  return pimpl->IsWarningEnabled();
}

bool Logger::IsInfoEnabled() const
{
  return pimpl->IsInfoEnabled();
}

bool Logger::IsDebugEnabled() const
{
  return pimpl->IsDebugEnabled();
}

bool Logger::IsTraceEnabled() const
{
  return pimpl->IsTraceEnabled();
}

void Logger::SetLogLevel(Level level)
{
  pimpl->SetLogLevel(level);
}

Level Logger::GetLogLevel() const
{
  return pimpl->GetLogLevel();
}

Level Logger::GetEffectiveLogLevel() const
{
  return pimpl->GetEffectiveLogLevel();
}


LoggerModule::LoggerModule(std::string const& module,
                           LoggerModulePtr const& parent)
  : module_(module)
  , level_(NotSpecified)
  , parent_(parent)
  , writer_(Writer::Instance())
{
}

LoggerModules::LoggerModules()
  : root_(new LoggerModule("", LoggerModulePtr()))
{
  // Make sure we have the root logger available.
  root_->SetLogLevel(Warning);
  modules_.insert(ModuleMap::value_type("", root_));
}

LoggerModules& LoggerModules::Instance()
{
  static LoggerModules instance;
  return instance;
}

LoggerModulePtr const& LoggerModules::GetModule(std::string const& module)
{
  std::string lower_module = boost::to_lower_copy(module);
  ModuleMap::iterator i = modules_.find(lower_module);
  if (i != modules_.end())
    return i->second;

  // Make the new LoggerModule and its parents.
  // Split on '.'
  std::string::size_type idx = lower_module.rfind(".");
  LoggerModulePtr parent = root_;
  if (idx != std::string::npos) {
    parent = GetModule(lower_module.substr(0, idx));
  }
  LoggerModulePtr logger(new LoggerModule(lower_module, parent));
  // std::map insert method returns a pair<iterator, bool> which seems
  // overly annoying to make a temporary of, so just return the const
  // reference pointed to by the interator.
  return modules_.insert(ModuleMap::value_type(lower_module, logger)).first->second;
}

void LoggerModules::reset()
{
  for (ModuleMap::iterator i = modules_.begin(), end = modules_.end(); i != end; ++i)
  {
    i->second->SetLogLevel(NotSpecified);
  }
}

std::string LoggerModules::dump_logging_levels(std::string const& prefix)
{
  std::ostringstream sout;
  bool first = true;
  for (ModuleMap::iterator i = modules_.begin(), end = modules_.end(); i != end; ++i)
  {
    std::string const& module_name = i->first;
    LoggerModulePtr const& module = i->second;
    Level severity = module->GetLogLevel();
    if (severity == NotSpecified)
      continue; // Don't write out unspecified ones.
    if (first)
      first = false;
    else
      sout << "\n";
    sout << prefix;
    if (module_name == "")
      sout << "<root>";
    else
      sout << module_name;
    sout << " " << str_level(severity);
  }
  return sout.str();
}


class LogStreamBuffer : public std::stringbuf
{
public:
  LogStreamBuffer(Level severity,
                  std::string const& module,
                  std::string const& filename,
                  int line_number);
protected:
  virtual int sync();
private:
  Level severity_;
  std::string module_;
  std::string filename_;
  int line_number_;
  std::time_t timestamp_;
};

LogStream::LogStream(Level severity,
                     std::string const& module,
                     std::string const& filename,
                     int line_number)
  : std::ostream(new LogStreamBuffer(severity, module,
                                     filename, line_number))
{
}

LogStream::~LogStream()
{
  rdbuf()->pubsync();
  std::streambuf* buff = rdbuf(0);
  delete buff;
}


LogStreamBuffer::LogStreamBuffer(Level severity,
                                 std::string const& module,
                                 std::string const& filename,
                                 int line_number)
  : std::stringbuf(std::ios_base::out)
  , severity_(severity)
  , module_(module)
  , filename_(filename)
  , line_number_(line_number)
  , timestamp_(std::time(0))
{
}

int LogStreamBuffer::sync()
{
  std::string message = str();
  // reset the stream
  str("");
  // Only log the message if there is something there.
  if (!message.empty())
    Writer::Instance().WriteMessage(severity_, module_,
                                    filename_, line_number_,
                                    timestamp_, message);
  return 0; // success
}

/**
 * A helper function for testing.  Not exported, but used in tests.
 *
 * Resets the root logger to warning, and sets all other modules to not
 * specified.
 */
void reset_logging()
{
  LoggerModules::Instance().reset();
}

std::string dump_logging_levels(std::string const& prefix)
{
  return LoggerModules::Instance().dump_logging_levels(prefix);
}

void configure_logging(const char* config_string)
{
  if (!config_string)
    return;
  std::vector<std::string> values;
  boost::split(values, config_string, boost::is_any_of(";:"));
  for (std::vector<std::string>::iterator i = values.begin(), end = values.end();
       i != end; ++i)
  {
    std::string& value = *i;
    std::string::size_type pos = value.find("=");
    if (pos != std::string::npos)
    {
      std::string name = value.substr(0, pos);
      std::string level = value.substr(pos+1);
      if (name == "<root>")
        name = "";
      Logger(name).SetLogLevel(get_logging_level(level));
    }
  }
}

Level get_logging_level(std::string level)
{
  boost::to_upper(level);
  if (level == "TRACE")
    return Trace;
  if (level == "DEBUG")
    return Debug;
  if (level == "INFO")
    return Info;
  if (level == "WARN" || level == "WARNING")
    return Warning;
  if (level == "ERROR")
    return Error;
  return Warning;
}

#if defined(NUX_OS_LINUX)
std::string Backtrace(int levels)
{
  std::ostringstream sout;
  void* trace[256];
  int n = ::backtrace(trace, 256);
  if (!n) {
    return sout.str();
  }

  char** strings = ::backtrace_symbols(trace, n);

  if (levels != -1) {
    n = std::min(n, levels);
  }

  for (int i = 0; i < n; ++i) {
    sout << i << ": " << strings[i] << '\n';
  }
  if (strings) {
    free (strings);
  }

  return sout.str();
}
#endif

BlockTracer::BlockTracer(Logger& logger,
                         Level level,
                         std::string const& function_name,
                         std::string const& filename,
                         int line_number)
  : logger_(logger)
  , level_(level)
  , function_name_(function_name)
  , filename_(filename)
  , line_number_(line_number)
{
  if (logger_.GetEffectiveLogLevel() <= level_)
  {
    LogStream(level_, logger_.module(), filename_, line_number_).stream()
      << "+" << function_name_;
  }
}

BlockTracer::~BlockTracer()
{
  if (logger_.GetEffectiveLogLevel() <= level_)
  {
    LogStream(level_, logger_.module(), filename_, line_number_).stream()
      << "-" << function_name_;
  }
}


namespace {
char const* str_level(Level severity)
{
  switch (severity)
  {
  case NotSpecified:
    return "NOT_SPECIFIED";
  case Trace:
    return "TRACE";
  case Debug:
    return "DEBUG";
  case Info:
    return "INFO";
  case Warning:
    return "WARNING";
  case Error:
    return "ERROR";
  case Critical:
    return "CRITICAL";
  }
  return "<unknown>";
}

}

} // namespace logging
} // namespace nux