revision: v0.14
Logger.h
Go to the documentation of this file.
1 //Copyright (c) 2013-2020, The MercuryDPM Developers Team. All rights reserved.
2 //For the list of developers, see <http://www.MercuryDPM.org/Team>.
3 //
4 //Redistribution and use in source and binary forms, with or without
5 //modification, are permitted provided that the following conditions are met:
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above copyright
9 // notice, this list of conditions and the following disclaimer in the
10 // documentation and/or other materials provided with the distribution.
11 // * Neither the name MercuryDPM nor the
12 // names of its contributors may be used to endorse or promote products
13 // derived from this software without specific prior written permission.
14 //
15 //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
16 //ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17 //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18 //DISCLAIMED. IN NO EVENT SHALL THE MERCURYDPM DEVELOPERS TEAM BE LIABLE FOR ANY
19 //DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20 //(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21 //LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22 //ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 //(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24 //SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 
26 #ifndef LOGGER_H
27 #define LOGGER_H
28 
29 #include <string>
30 #include <sstream>
31 #include <functional>
32 #include <type_traits>
33 #include <iomanip>
34 #include "GeneralDefine.h"
35 #include <iostream>
36 
37 #ifdef MERCURY_USE_MPI
38 #include "MpiContainer.h"
39 #endif
40 
41 #ifndef MERCURY_LOGLEVEL
42 #define MERCURY_LOGLEVEL Log::DEFAULT
43 #endif
44 
45 #ifndef CG_LOGLEVEL
46 #define CG_LOGLEVEL Log::DEFAULT
47 #endif
48 
49 #ifdef assert
50 #undef assert
51 //#error You included assert before the logger. Please use logger.assert_debug() instead.
52 #endif
53 
54 #ifdef MERCURY_FORCE_ASSERTS
55 #define MERCURY_ASSERTS true
56 #else
57 #ifdef MERCURY_NO_ASSERTS
58 #define MERCURY_ASSERTS false
59 #else
60 #ifdef NDEBUG
61 #define MERCURY_ASSERTS false
62 #else
63 #define MERCURY_ASSERTS true
64 #endif
65 #endif
66 #endif
67 
118 enum class Flusher
119 {
120  FLUSH,
121  NO_FLUSH
122 };
123 
132 enum class Log
133  : signed char
134 {
135  FATAL = -20, ERROR = -15, WARN = -10, INFO = -5, DEFAULT = 0, VERBOSE = 5, DEBUG = 10
136 };
137 
144 constexpr bool operator<=(const Log rhs, const Log lhs)
145 {
146  return ((static_cast<signed char>(rhs)) <= (static_cast<signed char>(lhs)));
147 }
148 
161 {
162 public:
163  std::function<void(std::string, std::string, Flusher)> onFatal;
164  std::function<void(std::string, std::string, Flusher)> onError;
165  std::function<void(std::string, std::string, Flusher)> onWarn;
166  std::function<void(std::string, std::string, Flusher)> onInfo;
167  std::function<void(std::string, std::string, Flusher)> onVerbose;
168  std::function<void(std::string, std::string, Flusher)> onDebug;
169 };
170 
179 extern LoggerOutput* loggerOutput;
180 
181 // Forward declaration..
182 template<Log L = Log::DEFAULT, bool ASSERTS = MERCURY_ASSERTS>
183 class Logger;
184 
197 template<Log Level>
198 class LL
199 {
200 public:
201 };
202 
219 extern LL<Log::FATAL> FATAL;
220 
233 extern LL<Log::ERROR> ERROR;
234 
246 extern LL<Log::WARN> WARN;
247 
258 extern LL<Log::INFO> INFO;
259 
266 
278 
289 extern LL<Log::DEBUG> DEBUG;
290 
307 template<Log L, bool ASSERTS>
308 class Logger
309 {
310 
311 private:
315  const std::string module;
320  Flusher doFlush_ = Flusher::FLUSH;
321 
322 public:
323 
329  explicit Logger(const std::string name)
330  : module(name)
331  {
332  }
333 
338  = default;
339 
353  template<Log LOGLEVEL, typename ... Args>
354  typename std::enable_if<!((L < LOGLEVEL) && (MERCURY_LOGLEVEL < LOGLEVEL)), void>::type
355  operator()(const LL<LOGLEVEL> log, const char* format UNUSED, Args&& ... arg UNUSED)
356  {
357  std::stringstream msgstream;
358  createMessage(msgstream, format, arg...);
359  if (LOGLEVEL <= Log::FATAL)
360  {
361  loggerOutput->onFatal(module, msgstream.str(), doFlush_);
362  }
363  else if (LOGLEVEL <= Log::ERROR)
364  {
365  loggerOutput->onError(module, msgstream.str(), doFlush_);
366  }
367  else if (LOGLEVEL <= Log::WARN)
368  {
369  loggerOutput->onWarn(module, msgstream.str(), doFlush_);
370  doFlush_ = Flusher::FLUSH;
371  }
372  else if (LOGLEVEL <= Log::INFO)
373  {
374  loggerOutput->onInfo(module, msgstream.str(), doFlush_);
375  doFlush_ = Flusher::FLUSH;
376  }
377  else if (LOGLEVEL <= Log::VERBOSE)
378  {
379  loggerOutput->onVerbose(module, msgstream.str(), doFlush_);
380  doFlush_ = Flusher::FLUSH;
381  }
382  else
383  {
384  loggerOutput->onDebug(module, msgstream.str(), doFlush_ = Flusher::FLUSH);
385  doFlush_ = Flusher::FLUSH;
386  }
387  }
388 
392  template<Log LOGLEVEL, typename... Args>
393  typename std::enable_if<L < LOGLEVEL && MERCURY_LOGLEVEL < LOGLEVEL, void>::type
394  operator()(const LL<LOGLEVEL> log, const char* format UNUSED, Args&& ... arg UNUSED)
395  {
396  }
397 
401  //std::string is sometimes convenient, but always slow, so where possible, don't convert the const char* to a string
402  //before converting it back
403  template<Log LOGLEVEL, typename... Args>
404  void operator()(const LL<LOGLEVEL> log, const std::string& format UNUSED, Args&& ... arg
405  UNUSED)
406  {
407  (*this)(log, format.c_str(), arg...);
408  }
409 
424  template<typename... Args>
425  typename std::enable_if<(ASSERTS) && (sizeof...(Args) >= 0), void>::type
426  assert_debug(bool assertion, const char* format, Args&& ... arg)
427  {
428  assert_always(assertion, format, arg...);
429  }
430 
431  template<typename... Args>
432  typename std::enable_if<!((ASSERTS) && sizeof...(Args) >= 0), void>::type
433  assert_debug(bool assertion, const char* format, Args&& ... arg)
434  {
435  }
436 
440  //the conversion from "" to a std::string is so slow, it takes 50% of the total run time for a release build...
441  template<typename... Args>
442  void assert_debug(bool assertion, const std::string format, Args&& ... arg)
443  {
444  assert_debug(assertion, format.c_str(), arg...);
445  }
446 
447  template<typename... Args>
448  void assert_always(bool assertion, const char* format, Args&& ... arg)
449  {
450  if (!assertion)
451  {
452  std::stringstream msgstream;
453  createMessage(msgstream, format, arg...);
454  loggerOutput->onFatal(module, msgstream.str(), doFlush_);
455  }
456 
457  }
458 
462  template<typename... Args>
463  void assert_always(bool assertion, const std::string format, Args&& ... arg)
464  {
465  assert_always(assertion, format.c_str(), arg...);
466  }
467 
472  template<typename... Args>
474  void log(const Log loglevel, const std::string& format, Args&& ... arg)
475  {
476  if (loglevel <= L || loglevel <= MERCURY_LOGLEVEL)
477  {
478  std::stringstream msgstream;
479  createMessage(msgstream, format.c_str(), arg...);
480  if (loglevel <= Log::FATAL)
481  {
482  loggerOutput->onFatal(module, msgstream.str(), doFlush_);
483  }
484  else if (loglevel <= Log::ERROR)
485  {
486  loggerOutput->onError(module, msgstream.str(), doFlush_);
487  }
488  else if (loglevel <= Log::WARN)
489  {
490  loggerOutput->onWarn(module, msgstream.str(), doFlush_);
491  doFlush_ = Flusher::FLUSH;
492  }
493  else if (loglevel <= Log::INFO)
494  {
495  loggerOutput->onInfo(module, msgstream.str(), doFlush_);
496  doFlush_ = Flusher::FLUSH;
497  }
498  else if (loglevel <= Log::VERBOSE)
499  {
500  loggerOutput->onVerbose(module, msgstream.str(), doFlush_);
501  doFlush_ = Flusher::FLUSH;
502  }
503  else
504  {
505  loggerOutput->onDebug(module, msgstream.str(), doFlush_ = Flusher::FLUSH);
506  doFlush_ = Flusher::FLUSH;
507  }
508  }
509  }
510 
511 private:
512 
527  template<typename Arg1, typename... Args>
528  void createMessage(std::stringstream& msg, const char* fmt,
529  Arg1&& arg, Args&& ... args)
530  {
531  bool doSkipNext = false;
532  while (*fmt != '%' || doSkipNext)
533  {
534  //Make sure we're not running past the end of our formatting string.
535  if (*fmt == '\0')
536  return;
537 
538  if (*fmt == '\\' && !doSkipNext)
539  { //Escape for the % character
540  doSkipNext = true;
541  fmt++;
542  }
543  else
544  {
545  msg << *fmt;
546  fmt++;
547  doSkipNext = false;
548  }
549  }
550  fmt++; //Consume the % character
551  int precision = 0;
552  int width = 0;
553  // if precision and width or only precision is defined
554  if (isdigit(*fmt))
555  {
556  precision = std::atoi(fmt);
557  while (isdigit(*fmt))
558  {
559  fmt++;
560  }
561  if (std::ispunct(*fmt))
562  {
563  fmt++;
564  if (std::isdigit(*fmt))
565  {
566  width = std::atoi(fmt);
567  while (isdigit(*fmt))
568  {
569  fmt++;
570  }
571  }
572  // else the char is a real full stop so set the pointer back to full stop.
573  else
574  {
575  fmt--;
576  }
577  }
578  }
579  // if only a width and no precision defined
580  else if (std::ispunct(*fmt))
581  {
582  fmt++;
583  if (std::isdigit(*fmt))
584  {
585  width = std::atoi(fmt);
586  while (isdigit(*fmt))
587  {
588  fmt++;
589  }
590  }
591  // else the char is a real full stop so set the pointer back to full stop.
592  else
593  {
594  fmt--;
595  }
596  }
597  if (width != 0 && precision != 0)
598  {
599  msg << std::setprecision(precision) << std::left << std::setw(width) << arg;
600  }
601  else if (precision != 0)
602  {
603  msg << std::setprecision(precision) << arg;
604  }
605  else if (width != 0)
606  {
607  msg << std::left << std::setw(width) << arg;
608  }
609  else
610  {
611  msg << arg;
612  } //include args somehow..
613  createMessage(msg, fmt, args...);//and recursively call ourselve / the method below.
614  }
615 
616 
627  //terminating case for Flusher not needed. This function is also called when the parameter pack Args&& args is
628  // empty
629  template<typename... Args>
630  void createMessage(std::stringstream& msg, const char* fmt,
631  Flusher arg, Args&& ... args)
632  {
633  // only suppress flushing if Mercury is not in CMAKE_BUILD_TYPE "Debug" and if the user defined loglevel from
634  // cMake is below VERBOSE/DEBUG (<=5)
635 #ifndef MERCURY_DEBUG
636  if (arg != Flusher::FLUSH && MERCURY_LOGLEVEL <= Log::VERBOSE)
637  {
639  }
640 #endif
641  // skip this argument by recursively calling this function again
642  createMessage(msg, fmt, args...);
643  }
644 
645 
654  // faster than above function and non recursive that is why it is good to have it
655  template<typename Arg1>
656  void createMessage(std::stringstream& msg, const char* fmt, Arg1&& arg)
657  {
658  bool doSkipNext = false;
659  while (*fmt != '%' || doSkipNext)
660  {
661  if (*fmt == '\0') // End of string
662  return;
663 
664  if (*fmt == '\\' && !doSkipNext)
665  { //Escape for the % character and the \ character
666  doSkipNext = true;
667  fmt++;
668  }
669  else
670  { //invoke the replacement
671  msg << *fmt;
672  fmt++;
673  doSkipNext = false;
674  }
675  }
676  fmt++; //Consume the % character
677  int precision = 0;
678  int width = 0;
679  // if precision and width or only precision is defined
680  if (isdigit(*fmt))
681  {
682  precision = std::atoi(fmt);
683  while (isdigit(*fmt))
684  {
685  fmt++;
686  }
687  if (std::ispunct(*fmt))
688  {
689  fmt++;
690  if (std::isdigit(*fmt))
691  {
692  width = std::atoi(fmt);
693  while (isdigit(*fmt))
694  {
695  fmt++;
696  }
697  }
698  // else the char is a real full stop so set the pointer back to full stop.
699  else
700  {
701  fmt--;
702  }
703  }
704  }
705  // if only a width and no precision defined
706  else if (std::ispunct(*fmt))
707  {
708  fmt++;
709  if (std::isdigit(*fmt))
710  {
711  width = std::atoi(fmt);
712  while (isdigit(*fmt))
713  {
714  fmt++;
715  }
716  }
717  // else the char is a real full stop so set the pointer back to full stop.
718  else
719  {
720  fmt--;
721  }
722  }
723  if (width != 0 && precision != 0)
724  {
725  msg << std::setprecision(precision) << std::left << std::setw(width) << arg << fmt;
726  }
727  else if (precision != 0)
728  {
729  msg << std::setprecision(precision) << arg << fmt;
730  }
731  else if (width != 0)
732  {
733  msg << std::left << std::setw(width) << arg << fmt;
734  }
735  else
736  {
737  msg << arg << fmt;
738  }
739  }
740 
741 
749  void createMessage(std::stringstream& msg, const char* message)
750  {
751  msg << message;
752  }
753 };
754 
764 
766 
767 //just emptying the functions is not sufficiently aggressive in disabling the actual (costly) comparison
768 #if !MERCURY_ASSERTS
769 #define assert(e,...) assert(true,"")
770 #endif
771 
772 #endif
cgLogger
Logger< CG_LOGLEVEL > cgLogger
LoggerOutput::onWarn
std::function< void(std::string, std::string, Flusher)> onWarn
Definition: Logger.h:165
printWarn
static void printWarn(std::string module, std::string msg, Flusher doFlush)
Prints messages of loglevel WARN.
Definition: Logger.cc:103
DEBUG
LL< Log::DEBUG > DEBUG
Debug information.
Definition: Logger.cc:58
VERBOSE
LL< Log::VERBOSE > VERBOSE
Verbose information.
Definition: Logger.cc:57
Flusher::FLUSH
@ FLUSH
Logger::createMessage
void createMessage(std::stringstream &msg, const char *fmt, Arg1 &&arg, Args &&... args)
Edits the message to a certain format and writes it to a stringstream by recursively replacing all % ...
Definition: Logger.h:528
logger
Logger< MERCURY_LOGLEVEL > logger("MercuryKernel")
Definition of different loggers with certain modules. A user can define its own custom logger here.
Flusher
Flusher
The Logger class provides ability to write log messages in your own customized format.
Definition: Logger.h:119
loggerOutputDefaultImpl
LoggerOutput loggerOutputDefaultImpl
Definition: Logger.cc:274
logger
Logger< MERCURY_LOGLEVEL > logger
Definition of different loggers with certain modules. A user can define its own custom logger here.
initialiseMPI
void initialiseMPI()
Inialises the MPI library.
Definition: MpiContainer.cc:137
MPIContainer::getProcessorID
std::size_t getProcessorID()
Reduces a scalar on all processors to one scalar on a target processor.
Definition: MpiContainer.cc:113
INFO
LL< Log::INFO > INFO
Info log level.
Definition: Logger.cc:55
MpiContainer.h
mathsFunc::log
Mdouble log(Mdouble Power)
Definition: ExtendedMath.cc:104
loggerOutput
LoggerOutput * loggerOutput
Declaration of the output functions.
Definition: Logger.cc:283
Log
Log
The different loglevels.
Definition: Logger.h:134
char
MERCURY_LOGLEVEL
#define MERCURY_LOGLEVEL
Definition: Logger.h:42
WARN
LL< Log::WARN > WARN
Warning log level.
Definition: Logger.cc:54
DEFAULT
LL< Log::DEFAULT > DEFAULT
Default log level.
Definition: Logger.cc:56
INFO
LL< Log::INFO > INFO
Info log level.
Definition: Logger.cc:55
printFatalError
static void printFatalError(const std::string &module, const std::string &msg, Flusher doFlush)
Prints messages of loglevel FATAL.
Definition: Logger.cc:206
LoggerOutput::onError
std::function< void(std::string, std::string, Flusher)> onError
Definition: Logger.h:164
DEBUG
LL< Log::DEBUG > DEBUG
Debug information.
Definition: Logger.cc:58
VERBOSE
LL< Log::VERBOSE > VERBOSE
Verbose information.
Definition: Logger.cc:57
ERROR
LL< Log::ERROR > ERROR
Error log level.
Definition: Logger.cc:53
Logger.h
MERCURY_DEPRECATED
#define MERCURY_DEPRECATED
Definition: GeneralDefine.h:37
Logger::doFlush_
Flusher doFlush_
Can prevent the logger from flushing the buffer via std::endl. doFlush_ is set automatically based on...
Definition: Logger.h:320
WARN
LL< Log::WARN > WARN
Warning log level.
Definition: Logger.cc:54
LL
Tag for template metaprogramming.
Definition: Logger.h:199
Log::FATAL
@ FATAL
Logger::operator()
std::enable_if<!((L< LOGLEVEL) &&(MERCURY_LOGLEVEL< LOGLEVEL)), void >::type operator()(const LL< LOGLEVEL > log, const char *format UNUSED, Args &&... arg UNUSED)
Log implementation of this function.
Definition: Logger.h:355
FATAL
LL< Log::FATAL > FATAL
Fatal log level.
Definition: Logger.cc:52
LoggerOutput::onFatal
std::function< void(std::string, std::string, Flusher)> onFatal
Definition: Logger.h:163
MPIContainer
This class contains all information and functions required for communication between processors.
Definition: MpiContainer.h:130
FATAL
LL< Log::FATAL > FATAL
Definition of the different loglevels by its wrapper class LL. These are used as tags in template met...
Definition: Logger.cc:52
Logger::createMessage
void createMessage(std::stringstream &msg, const char *message)
Terminating case / no argument call Overloaded function for a logger message without arguments.
Definition: Logger.h:749
constants::i
const std::complex< Mdouble > i
Definition: ExtendedMath.h:51
ERROR
LL< Log::ERROR > ERROR
Error log level.
Definition: Logger.cc:53
LoggerOutput
Default functions for output generation.
Definition: Logger.h:161
LoggerOutput::onDebug
std::function< void(std::string, std::string, Flusher)> onDebug
Definition: Logger.h:168
GeneralDefine.h
UNUSED
#define UNUSED
Definition: GeneralDefine.h:39
printError
static void printError(std::string module, std::string msg, Flusher doFlush)
Prints messages of loglevel ERROR.
Definition: Logger.cc:130
LoggerOutput::onVerbose
std::function< void(std::string, std::string, Flusher)> onVerbose
Definition: Logger.h:167
Logger
the Logger class is the main class of the logger implementation. It holds all the functions which inv...
Definition: Logger.h:309
Logger::createMessage
void createMessage(std::stringstream &msg, const char *fmt, Flusher arg, Args &&... args)
Overloaded version of createMessage to catch arguments of Flusher and suppress input flushing via std...
Definition: Logger.h:630
loggerOutput
LoggerOutput * loggerOutput
Declaration of the output functions.
Definition: Logger.cc:283
printInfo
static void printInfo(std::string module, std::string msg, Flusher doFlush)
Prints messages of loglevel INFO.
Definition: Logger.cc:76
operator<=
constexpr bool operator<=(const Log rhs, const Log lhs)
Internally used to filter on loglevel. Do not edit, as this is required for an optimised logger.
Definition: Logger.h:144
LoggerOutput::onInfo
std::function< void(std::string, std::string, Flusher)> onInfo
Definition: Logger.h:166
Logger::createMessage
void createMessage(std::stringstream &msg, const char *fmt, Arg1 &&arg)
Terminating case / Argument call. Overloaded function for a logger message with only one argument or ...
Definition: Logger.h:656
DEFAULT
LL< Log::DEFAULT > DEFAULT
Default log level.
Definition: Logger.cc:56
units::name
std::string name
Definition: MercuryProb.h:48
Logger::Logger
Logger(const std::string name)
constructor
Definition: Logger.h:329
cgLogger
Logger< CG_LOGLEVEL > cgLogger("MercuryCG")
Logger::module
const std::string module
The module name of this actual logger.
Definition: Logger.h:315
MPIContainer::Instance
static MPIContainer & Instance()
fetch the instance to be used for communication
Definition: MpiContainer.h:134
Logger::~Logger
~Logger()=default
destructor