fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <type_traits>
  4.  
  5. // macro for logging in a boost::log style
  6. #define LOGABLE_TYPE typename std::remove_reference<decltype(*this)>::type
  7. #define LOG_DEBUG this->Logable<LOGABLE_TYPE>::_loggerObj.logStream("debug")
  8. #define LOG_INFO this->Logable<LOGABLE_TYPE>::_loggerObj.logStream("info")
  9. #define LOG_WARN this->Logable<LOGABLE_TYPE>::_loggerObj.logStream("warning")
  10. #define LOG_ERROR this->Logable<LOGABLE_TYPE>::_loggerObj.logStream("error")
  11.  
  12.  
  13. class LogableImpl
  14. {
  15. private:
  16. std::string _channelName;
  17. public:
  18. LogableImpl(const std::string & channelName): _channelName(channelName) {}
  19.  
  20. std::ostream & logStream(const std::string & severetyLevel)
  21. {
  22. std::cout << _channelName << " " << severetyLevel;
  23. return std::cout;
  24. }
  25. };
  26.  
  27.  
  28. template <class Descendant>
  29. class Logable
  30. {
  31. protected:
  32. Logable(const std::string & channelName): _loggerObj(channelName) {}
  33. LogableImpl _loggerObj;
  34. };
  35.  
  36.  
  37. class Base: private Logable<Base>
  38. {
  39. public:
  40. Base()
  41. : Logable<Base>("Base")
  42. {}
  43.  
  44. void someMethod()
  45. {
  46. LOG_INFO << "some method is called" << std::endl;
  47. LOG_ERROR << "an error happened" << std::endl;
  48. }
  49. };
  50.  
  51.  
  52. class Derived: public Base, private Logable<Derived>
  53. {
  54. public:
  55. Derived()
  56. : Logable<Derived>("Derived")
  57. {}
  58.  
  59. void someAnotherMethod()
  60. {
  61. LOG_INFO << "another method is called" << std::endl;
  62. LOG_ERROR << "another error is happened" << std::endl;
  63. }
  64. };
  65.  
  66.  
  67. int main()
  68. {
  69. Base b;
  70. Derived d;
  71. b.someMethod();
  72. d.someMethod();
  73. d.someAnotherMethod();
  74.  
  75. return 0;
  76. }
Success #stdin #stdout 0s 3276KB
stdin
Standard input is empty
stdout
Base infosome method is called
Base erroran error happened
Base infosome method is called
Base erroran error happened
Derived infoanother method is called
Derived erroranother error is happened