#include "loglog.h" #include #include #include #include #include #include #include #include #include #define DEBUG_ENABLE 0 #define DATE_TIME_LEN 22 #define MAX_STDIN_DATA_LEN 1024 #define MAX_BUF_LEN MAX_STDIN_DATA_LEN+DATE_TIME_LEN #define MAX_PATH_OR_NAME_LEN 128 #define ERROR_MESSAGE "ERROR:The program may exit abnormally!\n" #if DEBUG_ENABLE #define debugf printf #else #define debugf #endif static char logFile[MAX_PATH_OR_NAME_LEN]={0}; static char buf[MAX_BUF_LEN]; static char dateTime[DATE_TIME_LEN+1]; static bool s_bOutput; static void* log_task(void *arg) { struct tm *pTm; time_t now; int fd; ssize_t size; char *pRet; struct stat fileStat; const char *fileName=(const char *)arg; int bReopen=0; FILE_REOPEN: fd=open(fileName,O_CREAT|O_WRONLY|O_APPEND,0644); if(fd==-1) { printf("open %s error\n",fileName); return ((void *)NULL); } else { bReopen=1; printf("open %s successfully!\n",fileName); } while(1) { if(bReopen==0&&stat(fileName,&fileStat)==0) { if(fileStat.st_size==0) { printf("%s was recreated by the outside world so reopen %s\n",fileName,fileName); close(fd); goto FILE_REOPEN; } } memset(buf,0,MAX_BUF_LEN); pRet=fgets(&buf[DATE_TIME_LEN],MAX_STDIN_DATA_LEN-1,stdin); if(pRet==NULL) { strcpy(&buf[DATE_TIME_LEN],ERROR_MESSAGE); } now=time(NULL); pTm=localtime((const time_t *)&now); if(pTm==NULL) { debugf("localtime is NULL!\n"); return (void *)NULL; } sprintf(dateTime,"[%04d-%02d-%02d %02d:%02d:%02d] ", pTm->tm_year+1900,pTm->tm_mon+1,pTm->tm_mday, pTm->tm_hour,pTm->tm_min,pTm->tm_sec); strncpy(buf,dateTime,DATE_TIME_LEN); debugf("dateTime:%s\n",dateTime); if(s_bOutput) { printf("%s",buf); } size=strlen(&buf[DATE_TIME_LEN]); size=write(fd,buf,DATE_TIME_LEN+size); if(size>0) { bReopen=0; debugf("write to %s :\nlen :%d\ndata :%s\n",fileName,size,buf); } if(pRet==NULL) { debugf(ERROR_MESSAGE); break; } } close(fd); exit(-1); } void log_init(const char *logPath,const char *logName,bool bOutput) { pthread_t threadLog; setvbuf(stdout, NULL, _IONBF, 0); assert( logPath!=NULL && logName!=NULL ); sprintf(logFile,"%s%s",logPath,logName); s_bOutput=bOutput; printf("<%s> logPath:%s logName:%s %s\n",__FUNCTION__,logPath,logName,s_bOutput?"proutlog":"noprout"); log_task((void *)logFile); }