alog.h 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. #ifndef ALOG_H
  2. #define ALOG_H
  3. #include <stdarg.h>
  4. #include <string.h>
  5. #include <fstream>
  6. #include <string>
  7. #ifndef __FILENAME__
  8. #ifdef _WIN32
  9. #define __FILENAME__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)
  10. #else
  11. #define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
  12. #endif
  13. #endif
  14. // Global Logger class
  15. namespace iv {
  16. class Logger
  17. {
  18. private:
  19. Logger()
  20. {
  21. mbFileOpen = false;
  22. mbCallBack = false;
  23. }
  24. ~Logger()
  25. {
  26. }
  27. public:
  28. static Logger & Inst()
  29. {
  30. static iv::Logger instance_;
  31. return instance_;
  32. }
  33. void Log(char const* file, char const* func, int line, char const* format, ...)
  34. {
  35. static char complete_entry[2048];
  36. static char message[1024];
  37. va_list args;
  38. va_start(args, format);
  39. vsnprintf(message, 1024, format, args);
  40. #ifndef DEBUG_NOTRACE
  41. snprintf(complete_entry, 2048, "%s | %s() | %d: %s", file, func,line, message);
  42. #else
  43. strncpy(complete_entry, message, 1024);
  44. #endif
  45. va_end(args);
  46. if((!mbFileOpen) &&(!mbCallBack))
  47. printf("%s\n", complete_entry);
  48. else
  49. {
  50. if(mbFileOpen)
  51. {
  52. file_ << complete_entry << std::endl;
  53. file_.flush();
  54. }
  55. if(mbCallBack)
  56. {
  57. callback_(complete_entry);
  58. }
  59. }
  60. }
  61. void setlogfile(std::string strfilepath)
  62. {
  63. if (file_.is_open())
  64. {
  65. // Close any open logfile, perhaps user want a new with unique filename
  66. file_.close();
  67. }
  68. file_.open(strfilepath.c_str());
  69. if (file_.fail())
  70. {
  71. mbFileOpen = false;
  72. printf("Cannot open log file: %s \n",
  73. strfilepath.c_str());
  74. }
  75. else
  76. {
  77. mbFileOpen = true;
  78. }
  79. }
  80. typedef void(*FuncPtr)(const char*);
  81. void SetCallback(FuncPtr callback)
  82. {
  83. callback_ = callback;
  84. if(callback_ != 0)mbCallBack = true;
  85. else mbCallBack = false;
  86. }
  87. bool IsCallbackSet()
  88. {
  89. return callback_ != 0;
  90. }
  91. bool IsFileOpen() { return file_.is_open(); }
  92. private:
  93. FuncPtr callback_ = 0;
  94. std::ofstream file_;
  95. bool mbFileOpen;
  96. bool mbCallBack;
  97. };
  98. }
  99. #ifndef NOTUSEALOG
  100. #define ALOG(Format_, ...) iv::Logger::Inst().Log(__FILENAME__, __FUNCTION__, __LINE__, Format_, ##__VA_ARGS__)
  101. #else
  102. #define ALOG(Format_, ...)
  103. #endif
  104. #endif