#pragma once #include <windows.h> #include <process.h> class CLogger { public: static CRITICAL_SECTION m_cs;//保证所有的对象都能访问到它 public: CLogger(); ~CLogger(); static int logger_to_file(const char* logfile);//加锁,放锁 static int logger(const char* fmt, ...); static int close_logger_file(); private: static int log_ref; static FILE* logfp; }; // namespace Logger // { // int logger_to_file(const char* logfile); // int logger(const char* fmt, ...); // int close_logger_file(); // int log_ref; // FILE* logfp; // } #pragma once #include "stdafx.h" #include <stdarg.h> #include <stdio.h> #include <iostream> #include <time.h> #include "log.h" using namespace std; int CLogger::log_ref = 0; FILE* CLogger::logfp = NULL; std::string get_current_time(); CRITICAL_SECTION CLogger::m_cs = {}; CLogger::CLogger() { } CLogger::~CLogger() { close_logger_file(); } int CLogger::logger_to_file(const char* logfile) { if (log_ref++ == 0) //保证只有为0打开,与关闭对应起来 { InitializeCriticalSection(&m_cs); logfp = fopen(logfile, "w+b"); if (!logfp) { log_ref--; return -1; } } return 0; } int CLogger::logger(const char* fmt, ...) { EnterCriticalSection(&m_cs); static char buffer[10240]; va_list va; int ret = 0; va_start(va, fmt); vsprintf(buffer, fmt, va); std::string time = get_current_time(); // 输出到文件. if (logfp) { fprintf(logfp, "[%s] %s", time.c_str(), buffer); fflush(logfp); } // 输出到屏幕. ret = printf("[%s] %s", time.c_str(), buffer); va_end(va); EnterCriticalSection(&m_cs); return ret; } int CLogger::close_logger_file() { if (!logfp) return -1; if (--log_ref == 0) { fclose(logfp); logfp = NULL; DeleteCriticalSection(&m_cs); } return 0; } std::string get_current_time() { char buffer[1024] = {0}; std::string ret; struct tm curr_time; time_t tmp_time; time(&tmp_time); curr_time = *(localtime(&tmp_time)); if (curr_time.tm_year > 50) { sprintf(buffer, "%04d-%02d-%02d %02d:%02d:%02d", curr_time.tm_year + 1900, curr_time.tm_mon + 1, curr_time.tm_mday, curr_time.tm_hour, curr_time.tm_min, curr_time.tm_sec); } else { sprintf(buffer, "%04d-%02d-%02d %02d:%02d:%02d", curr_time.tm_year + 2000, curr_time.tm_mon + 1, curr_time.tm_mday, curr_time.tm_hour, curr_time.tm_min, curr_time.tm_sec); } return std::string(buffer); }