1 2#include <stdarg.h> 3#include <time.h> 4#include <stdio.h> 5#include <memory.h> 6#include <string.h> 7#include <sys/timeb.h> 8 9#include "log.h" 10 11#define BUFSIZE 4096 12 13#ifdef _WIN32 14#define snprintf _snprintf 15#endif 16 17FILE *logFile = NULL; 18int logLevel = 20; 19 20const char *logTime() 21{ 22 static char buf[128]; 23 char *p = 0; 24 time_t lTime; 25 struct tm *tm1; 26 27 time(&lTime); 28 tm1 = localtime(&lTime); 29 strcpy(buf, asctime(tm1)); 30 p = strchr(buf, '\n'); 31 32 if (p) *p = '\0'; 33 return buf; 34} 35 36void log_open(const char *file, int level) 37{ 38 logLevel = level; 39 40 if (logFile) 41 log_close(); 42 43 if (file && *file) 44 logFile = fopen(file, "a+"); 45 if (!logFile) 46 { 47 logFile = stderr; 48 if (file && *file) 49 LOG(1) ("Error open log file: %s\n", file); 50 } 51 //for test only!!! 52 //logFile = stderr; 53} 54 55void log_close() 56{ 57 if (logFile && logFile != stderr) { 58 fclose(logFile); 59 logFile = NULL; 60 } 61} 62 63void log_print(const char *fmt, ...) 64{ 65 char buf[BUFSIZE]; 66 67 va_list args; 68 va_start(args, fmt); 69 70 snprintf(buf, sizeof(buf), "%s| %s", logTime(), fmt); 71 if(logFile) { 72 vfprintf(logFile, buf, args); 73 fflush(logFile); 74 } 75 76 va_end(args); 77} 78