⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 logadmin.cpp

📁 LINUX C++开发的写日志函数源嘛
💻 CPP
字号:


#define MAX_FILE_NUMBER	20
#define MAX_FILE_LINES	100000

#define LOG_NORMAL     " DEBUG"
#define LOG_WARN       " NORMAL"
#define LOG_ERROR      " ALERT"

char g_ProgramName[32];
char gsLogFilePath[128];

short int g_nLogFd;
char gsLogFileName[128];

short int g_nLogWarnFd;
char gsLogWarnFileName[128];

short int g_nLogErrorFd;
char gsLogErrorFileName[128];
short int g_nLogLevel;


int CurrentDay = 0;			//当前天
int OldDay = 0;				//昨天

int nLogTimes = 0;		//次数
int nWarnTimes = 0 ;	//次数
int nErrorTimes = 0;	//错误次数

void WriteFile(short int *,char *,char *);
short int OpenFile(char *);
short int MakeDirectory(char *);


/************************************************************

 *Description:
 *  According the input log file name, open the log file
 *Input:
 *  N/A
 *Output:
 *  N/A
 *Return: nFd if success, -1 failed
 *Errors:
 *Cautions:
 ************************************************************/
short int OpenLog()
{
	char sTmpMsg[160];
	short int nFd;
	
    time_t nCurTime;
    struct tm rGmTime;
    struct timeval rTimeval;
    struct timezone rTimeZone;

    time(&nCurTime);
    localtime_r(&nCurTime,&rGmTime);
    gettimeofday(&rTimeval,&rTimeZone);

	CurrentDay = rGmTime.tm_mday;
	OldDay = CurrentDay;


	strcpy(gsLogFileName,gsLogFilePath);
	strcat(gsLogFileName,"debug/");

	strcpy(gsLogWarnFileName,gsLogFilePath);
	strcat(gsLogWarnFileName,"normal/");

	strcpy(gsLogErrorFileName,gsLogFilePath);
	strcat(gsLogErrorFileName,"alert/");

	printf("gsLogFilePath = %s, gsLogErrorFileName = %s\n",gsLogFilePath, gsLogErrorFileName);

	g_nLogFd=OpenFile(gsLogFileName);
	if(g_nLogFd<0)
	{
        sprintf(sTmpMsg,"Can't open log file [%s],Exit...\n",gsLogFileName);
        DisplayPromptMsg(sTmpMsg);
		return -1;
	}

	g_nLogWarnFd=OpenFile(gsLogWarnFileName);
	if(g_nLogWarnFd<0)
	{
        sprintf(sTmpMsg,"Can't open log file [%s],Exit...\n",gsLogWarnFileName);
        DisplayPromptMsg(sTmpMsg);
		return -1;
	}

	g_nLogErrorFd=OpenFile(gsLogErrorFileName);
	if(g_nLogErrorFd<0)
	{
        sprintf(sTmpMsg,"Can't open log file [%s],Exit...\n",gsLogErrorFileName);
        DisplayPromptMsg(sTmpMsg);
		return -1;
	}

	return 0;
}

/************************************************************
 *Name:WriteLog
 *Description:
 *  write messages into log files
 *Input:
 *  sTmpMsg:to be record message
 *  nMsgLevel:message level,if below log level,don't write log,
 *  else write this message
 *  nFormat: 0 if text message,  1 if binary message
 *Output:
 *  N/A
 *Return: N/A
 *Errors:
 *Cautions:
 ************************************************************/
void WriteLog(char *sTmpMsg, short int nMsgLevel)
{
    time_t nCurTime;
    struct tm rGmTime;
    struct timeval rTimeval;
    struct timezone rTimeZone;
    char sBuf[1024]={0};

	if(g_nLogLevel>nMsgLevel)
		return;

	if(g_nLogFd<0)
		return;

    time(&nCurTime);
    localtime_r(&nCurTime,&rGmTime);
    gettimeofday(&rTimeval,&rTimeZone);

	CurrentDay = rGmTime.tm_mday;
	
	switch(nMsgLevel)
	{
		case 0:
  			sprintf(sBuf,"%02d %02d:%02d:%02d:%06d %s ",
                rGmTime.tm_mday,rGmTime.tm_hour,rGmTime.tm_min,rGmTime.tm_sec,
				rTimeval.tv_usec,LOG_NORMAL);
			strcat(sBuf,sTmpMsg);
			WriteFile(&g_nLogFd,sBuf,gsLogFileName);

			if(CurrentDay!=OldDay)
			{
				close(g_nLogFd);
				g_nLogFd=OpenFile(gsLogFileName);
			}

			break;
		case 1:
  			sprintf(sBuf,"%02d %02d:%02d:%02d:%06d %s ",
                rGmTime.tm_mday,rGmTime.tm_hour,rGmTime.tm_min,rGmTime.tm_sec,
				rTimeval.tv_usec,LOG_WARN);
			strcat(sBuf,sTmpMsg);
			WriteFile(&g_nLogWarnFd,sBuf,gsLogWarnFileName);
			
			if(CurrentDay!=OldDay)
			{
				close(g_nLogWarnFd);
				g_nLogWarnFd=OpenFile(gsLogWarnFileName);
			}
			break;
		default:
  			sprintf(sBuf,"%02d %02d:%02d:%02d:%06d %s ",
                rGmTime.tm_mday,rGmTime.tm_hour,rGmTime.tm_min,rGmTime.tm_sec,
				rTimeval.tv_usec,LOG_ERROR);
			strcat(sBuf,sTmpMsg);
			WriteFile(&g_nLogWarnFd,sBuf,gsLogErrorFileName);
			if(CurrentDay!=OldDay)
			{
				close(g_nLogErrorFd);
				g_nLogErrorFd=OpenFile(gsLogErrorFileName);
			}


	}
	return;
}

/************************************************************
 *Name:CloseLog
 *Description:
 *  Close the special Log File
 *Input:
 *  nFd: handle of the file
 *Output:
 *  N/A
 *Return:
 *  N/A
 *Errors:
 *Cautions:
 ************************************************************/
void CloseLog(short int nFd)
{
	close(nFd);
	return;
}

void CreateBinLogLine(char *sBuf,int nLen,char *sPrompt,char *sItem, 
															int nInputLen)
{
	unsigned char c;
	int nAddLen = 0;
	int i;

	sBuf[0] = '\0';

	if ( nLen < 30 )
		return;

	/*
	 * add Prompt string to sBuf
	 */
	nAddLen=strlen(sPrompt);
	if(nLen<(nAddLen+1))
		return;
	else
		strcat(sBuf, sPrompt);

	/*
	 * add item string to sBuf
	 */
	nLen -= 1;
	i = 0;
	while((i++<nInputLen)&&(nAddLen<nLen))
	{
		c=*sItem++;
		if(nAddLen+4<nLen)
		{
			sprintf( sBuf+nAddLen, "[%02x]", c );
			nAddLen += 4;
		}
		else
			break;
	}

	sBuf[nAddLen] = '\0';
	return;
}

/*
 *display prompt msg on stdout
 */
int DisplayPromptMsg(char *sPromptMsg )
{
    printf("%s\n",sPromptMsg);
    return 0;
}

short int OpenFile(char *pFileName)
{
	time_t			CrentTime;
	struct tm		today; 
	struct tm		*ptoday; 
	short int nFd=-1;

	char			FileName[128];

	/*构造文件名前缀*/
	time(&CrentTime);
	memset(&today,0,sizeof(today));
	ptoday=localtime(&CrentTime);
	memcpy(&today,ptoday,sizeof(today));

	CurrentDay = today.tm_mday;
	if(CurrentDay!=OldDay)
	{
		OldDay = CurrentDay;
		nLogTimes = 0;
		nWarnTimes = 0;
		nErrorTimes = 0;
	}

	if(strstr(pFileName,"/debug/")!=NULL)
	{
		if(nLogTimes>0)
		{
			sprintf(FileName,"%s%s_%04d%02d%02d_%d.log",pFileName, g_ProgramName, today.tm_year+1900,
					today.tm_mon+1,today.tm_mday,nLogTimes);
		}
		else
		{
			sprintf(FileName,"%s%s_%04d%02d%02d.log",pFileName, g_ProgramName, today.tm_year+1900,
					today.tm_mon+1,today.tm_mday);
		}
		nLogTimes++;
	}
	else if(strstr(pFileName,"/normal/")!=NULL)
	{
		if(nWarnTimes>0)
		{
			sprintf(FileName,"%s%s_%04d%02d%02d_%d.log",pFileName, g_ProgramName, today.tm_year+1900,
					today.tm_mon+1,today.tm_mday,nWarnTimes);
		}
		else
		{
			sprintf(FileName,"%s%s_%04d%02d%02d.log",pFileName, g_ProgramName, today.tm_year+1900,
					today.tm_mon+1,today.tm_mday);
		}
		nWarnTimes++;
	}
	else if(strstr(pFileName,"/alert/")!=NULL)
	{
		if(nErrorTimes>0)
		{
			sprintf(FileName,"%s%s_%04d%02d%02d_%d.log",pFileName, g_ProgramName, today.tm_year+1900,
					today.tm_mon+1,today.tm_mday,nErrorTimes);
		}
		else
		{
			sprintf(FileName,"%s%s_%04d%02d%02d.log",pFileName, g_ProgramName, today.tm_year+1900,
					today.tm_mon+1,today.tm_mday);
		}
		nErrorTimes++;
	}
	else
	{
		if(nLogTimes>0)
		{
			sprintf(FileName,"%s%s_%04d%02d%02d_%d.log",pFileName, g_ProgramName, today.tm_year+1900,
					today.tm_mon+1,today.tm_mday,nLogTimes);
		}
		else
		{
			sprintf(FileName,"%s%s_%04d%02d%02d.log",pFileName, g_ProgramName, today.tm_year+1900,
					today.tm_mon+1,today.tm_mday);
		}
		nLogTimes++;
	}

	//nFd = open(FileName,O_RDWR|O_CREAT,0666);
	nFd = open( FileName,O_RDWR|O_CREAT|O_APPEND,0666 );
	if(nFd<=2)
		return -1;
	else 
		return nFd;

    return -1;
}

short int MakeDirectory(char *pDir)
{
    struct stat rStat;

    if(stat(pDir,&rStat)!=0)      //Not exist,then create it

    {
        if(mkdir(pDir,S_IEXEC|S_IREAD|S_IWRITE|S_IRGRP|S_IWGRP|S_IXGRP
                                            |S_IROTH|S_IWOTH|S_IXOTH)!=0)
            return -1;
        return 0;
    }

    if(!S_ISDIR(rStat.st_mode))  //Exist,but is not a directory,then creat it
    {
        if(mkdir(pDir,S_IEXEC|S_IREAD|S_IWRITE|S_IRGRP|S_IWGRP|S_IXGRP
                                            |S_IROTH|S_IWOTH|S_IXOTH)!=0)
            return -1;
        return 0;
    }

    return 0;
}

void WriteFile(short int *pFd,char *pInput,char *pFileName)
{
    static long nLines=0;
    short int nLen=0;

    nLen=strlen(pInput);
    write(*pFd,pInput,nLen);
    write(*pFd,"\n",1);

    nLines++;
    if(nLines<MAX_FILE_LINES)
        return;
    close(*pFd);

    nLines=0;
    *pFd=OpenFile(pFileName);
    return;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -