#include "logger/Logger.h" #include SysLogger* SysLogger::instance_ = NULL; SysLogger* SysLogger::GetInstance() { if (instance_ == NULL) { instance_ = new SysLogger(); } return instance_; } SysLogger::SysLogger(): m_minLevel(0), m_fp(NULL), m_isStarted(false) { m_logFileName = new char[MAX_FILENAME_LEN]; memset(m_logFileName, 0, MAX_FILENAME_LEN); m_logBuf = new char[LOG_BUF_SIZE]; } SysLogger::~SysLogger() { if (m_logFileName != NULL) { delete[] m_logFileName; m_logFileName = NULL; } if (m_logBuf != NULL) { delete[] m_logBuf; m_logBuf = NULL; } if (m_fp != NULL) { fclose(m_fp); m_fp = NULL; } } bool SysLogger::InitLogger(const char* file_name, int min_level) { if(m_isStarted){ return true; } m_isStarted = true; //strncpy(m_logFileName, file_name, MAX_FILENAME_LEN - 1); strncpy_s(m_logFileName, MAX_FILENAME_LEN - 1, file_name, MAX_FILENAME_LEN - 1); if (min_level >=0 && min_level <= 4) { m_minLevel = min_level; } //m_fp = fopen(m_logFileName, "a"); //if (m_fp == NULL) { // return false; //} errno_t err = fopen_s(&m_fp, m_logFileName, "a"); if(err != 0) { return false; } return true; } void SysLogger::WriteLog(int level, const char* exec_file, const char*func, int exec_line, int tid, const char* format, ...) { if(!m_isStarted){ return; } if (level < m_minLevel) { return; } m_mutex.lock(); va_list valst; va_start(valst, format); set_log(level, exec_file, func,exec_line, tid, format, valst); va_end(valst); #ifdef LOGGER_CONSOLE std::cout << m_logBuf < [%s:%s:%d] [%d] ", sys.wYear, sys.wMonth, sys.wDay, sys.wHour, sys.wMinute, sys.wSecond, sys.wMilliseconds, levstr, exec_filename, func, exec_line, tid); #else struct timeval now = { 0, 0 }; gettimeofday(&now, NULL); struct tm* sys_tm = localtime(&(now.tv_sec)); int n = snprintf(m_logBuf, 128, "\n%d-%02d-%02d %02d:%02d:%02d,%03d <%s> [%s:%s:%d] [%d] ", sys_tm->tm_year + 1900, sys_tm->tm_mon + 1, sys_tm->tm_mday, sys_tm->tm_hour, sys_tm->tm_min, sys_tm->tm_sec, now.tv_usec / 1000, levstr, exec_filename, func, exec_line, tid); #endif vsnprintf(m_logBuf + n, LOG_BUF_SIZE - n, format, valst); }