| #ifndef __log_h__ #define __log_h__ #include <stdio.h> #include <tchar.h> #include <crtdbg.h> #include <windows.h> #include <time.h> #include <sys timeb.h= "" > Class CLog { Public ~clog (); Static clog* Get (tchar* path = NULL); void printf (const char* format, ...); Private CLog (file* handle); Private Static clog* _log; File* _handle; }; enum { Log_debug, Log_info, Log_warn, Log_error, Log_fatal }; #ifdef _DEBUG static unsigned int log_level = Log_debug; #else static unsigned int log_level = Log_info; #endif #define PRINT_LINE (type, format, datetime, MS, ...) \ printf ("%lu::%s::%s,%.3d::%s::" format "\ \", GetCurrentThreadID (), type, datetime, MS, \ __function__, # # __va_args__); #define LOG (type, format, ...) do {\ if (type >= log_level && type <= log_fatal) {\ clog* log = Clog::get (); \ const char *type_as_char[] = {"DEBUG", "INFO", "WARN", "ERROR", "FATAL"}; \ struct _TIMEB now; \ struct TM today; \ Char datetime_str[20]; \ _ftime_s (&now); \ localtime_s (&today, &now.time); \ Strftime (Datetime_str, "%y-%m-%d%h:%m:%s", &today); \ if (log) {\ Log->print_line (Type_as_char[type], format, DATETIME_STR, NOW.MILLITM, # # __va_args__); \ } else {\ Print_line (Type_as_char[type], format, DATETIME_STR, NOW.MILLITM, # # __va_args__); \ } \ } \ } while (0) #define LOG_PRINTF (format, ...) LOG (Log_info, format, # # __va_args__) #define LOG_INFO (format, ...) LOG (Log_info, format, # # __va_args__) #define LOG_WARN (format, ...) LOG (Log_warn, format, # # __va_args__) #define LOG_ERROR (format, ...) LOG (Log_error, format, # # __va_args__) #define DBGLEVEL 1000 #define DBG (level, format, ...) do {\ if (level <= dbglevel) {\ LOG (Log_debug, format, # # __va_args__); \ } \ } while (0) #define ASSERT (x) _asserte (x) #endif </sys></time.h></windows.h></crtdbg.h></tchar.h></stdio.h> Log.cpp #include "Log.h" #include <stdio.h> #include <stdarg.h> #include <share.h> #define LOG_ROLL_SIZE (1024 * 1024) clog* clog::_log = NULL; Clog::clog (file* handle) : _handle (handle) { _log = this; } Clog::~clog () { if (_log && _handle) { Fclose (_handle); _log = NULL; } } clog* clog::get (char* path) { if (_log) { return _log; } if (!path) { Path = "Dll.log"; } DWORD size = 0; HANDLE file = CreateFile (path, generic_read, 0, NULL, open_existing, File_attribute_normal, NULL); if (file!= invalid_handle_value) { Size = GetFileSize (file, NULL); CloseHandle (file); } if (size!= invalid_file_size && size > Log_roll_size) { TCHAR Roll_path[max_path]; sprintf (Roll_path, "%s.1", Path); if (! MoveFileEx (Path, Roll_path, movefile_replace_existing)) { return NULL; } } file* handle = fopen (path, "A +"); if (!handle) { return NULL; } _log = new CLog (handle); return _log; } void CLog::p rintf (const char* format, ...) { Va_list args; Va_start (args, format); vfprintf (_handle, format, args); Va_end (args); Fflush (_handle); } </share.h></stdarg.h></stdio.h> |