#include #include #include #include #include "log.h" int debug = 0; #ifdef _WIN32 #include #include #include static const WORD MAX_CONSOLE_LINES = 500; void logit(int type, const char * format, ...) { static int hConHandle = 0; if (0 && hConHandle == 0) { CONSOLE_SCREEN_BUFFER_INFO coninfo; AllocConsole(); if (AttachConsole(ATTACH_PARENT_PROCESS) == ERROR_INVALID_HANDLE) { AllocConsole(); } GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo); coninfo.dwSize.Y = MAX_CONSOLE_LINES; SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize); int hConHandle; long lStdHandle; FILE *fp; // redirect unbuffered STDOUT to the console lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "w" ); *stdout = *fp; setvbuf( stdout, NULL, _IONBF, 0 ); // redirect unbuffered STDIN to the console lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "r" ); *stdin = *fp; setvbuf( stdin, NULL, _IONBF, 0 ); // redirect unbuffered STDERR to the console lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "w" ); *stderr = *fp; setvbuf( stderr, NULL, _IONBF, 0 ); } va_list va; va_start(va, format); struct timeval now; gettimeofday(&now, NULL); struct tm * now_tm = localtime(&(now.tv_sec)); if (type == LOG_INFO) { vfprintf(stdout, format, va); fprintf(stdout, "\n"); } else if (type == LOG_DEBUG) { if (debug > 0) { fprintf(stderr, "%02d:%02d:%02d.%03d ", now_tm->tm_hour, now_tm->tm_min, now_tm->tm_sec, (int)(now.tv_usec / 1000)); vfprintf(stderr, format, va); fprintf(stderr, "\n"); } } else { vfprintf(stderr, format, va); fprintf(stderr, "\n"); } va_end(va); } #else void logit(int type, const char * format, ...) { va_list va; va_start(va, format); struct timeval now; gettimeofday(&now, NULL); struct tm * now_tm = localtime(&(now.tv_sec)); if (type == LOG_INFO) { vfprintf(stdout, format, va); fprintf(stdout, "\n"); } else if (type == LOG_DEBUG) { if (debug > 0) { fprintf(stderr, "%02d:%02d:%02d.%03d ", now_tm->tm_hour, now_tm->tm_min, now_tm->tm_sec, (int)(now.tv_usec / 1000)); vfprintf(stderr, format, va); fprintf(stderr, "\n"); } } else { vfprintf(stderr, format, va); fprintf(stderr, "\n"); } va_end(va); } #endif