123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134 |
- #ifndef ALOG_H
- #define ALOG_H
- #include <stdarg.h>
- #include <string.h>
- #include <fstream>
- #include <string>
- #ifndef __FILENAME__
- #ifdef _WIN32
- #define __FILENAME__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)
- #else
- #define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
- #endif
- #endif
- // Global Logger class
- namespace iv {
- class Logger
- {
- private:
- Logger()
- {
- mbFileOpen = false;
- mbCallBack = false;
- }
- ~Logger()
- {
- }
- public:
- static Logger & Inst()
- {
- static iv::Logger instance_;
- return instance_;
- }
- void Log(char const* file, char const* func, int line, char const* format, ...)
- {
- static char complete_entry[2048];
- static char message[1024];
- va_list args;
- va_start(args, format);
- vsnprintf(message, 1024, format, args);
- #ifndef DEBUG_NOTRACE
- snprintf(complete_entry, 2048, "%s | %s() | %d: %s", file, func,line, message);
- #else
- strncpy(complete_entry, message, 1024);
- #endif
- va_end(args);
- if((!mbFileOpen) &&(!mbCallBack))
- printf("%s\n", complete_entry);
- else
- {
- if(mbFileOpen)
- {
- file_ << complete_entry << std::endl;
- file_.flush();
- }
- if(mbCallBack)
- {
- callback_(complete_entry);
- }
- }
- }
- void setlogfile(std::string strfilepath)
- {
- if (file_.is_open())
- {
- // Close any open logfile, perhaps user want a new with unique filename
- file_.close();
- }
- file_.open(strfilepath.c_str());
- if (file_.fail())
- {
- mbFileOpen = false;
- printf("Cannot open log file: %s \n",
- strfilepath.c_str());
- }
- else
- {
- mbFileOpen = true;
- }
- }
- typedef void(*FuncPtr)(const char*);
- void SetCallback(FuncPtr callback)
- {
- callback_ = callback;
- if(callback_ != 0)mbCallBack = true;
- else mbCallBack = false;
- }
- bool IsCallbackSet()
- {
- return callback_ != 0;
- }
- bool IsFileOpen() { return file_.is_open(); }
- private:
- FuncPtr callback_ = 0;
- std::ofstream file_;
- bool mbFileOpen;
- bool mbCallBack;
- };
- }
- #ifndef NOTUSEALOG
- #define ALOG(Format_, ...) iv::Logger::Inst().Log(__FILENAME__, __FUNCTION__, __LINE__, Format_, ##__VA_ARGS__)
- #else
- #define ALOG(Format_, ...)
- #endif
- #endif
|