最近在做游戏开发,阅读了一些源码后做了一些总结与记录,希望对自己和其他的朋友有所帮助。软件开发中常常将关键的操作、一般性警告以及严重的错误,通过字符串的形式输出至日志文件,本子系统实现bootlog,debuglog,warning,fatallog等输出形式,支持多线程。有不到之处欢迎指正,交流。email:caohaitao_linux@163.com

LoLog日志系统关键知识

1.文件操作

2.获取当前时间的字符串

3.变参函数的处理


LoLog组成要素

1.文件指针

2.文件状态(可省)

3.互斥锁

注:文件状态可以通过判断文件指针是否为空来获得,但此过程使用频繁,以函数调用形式会使得压栈弹、栈操作过多。static int占用空间较少,变量见名知意使用方便,最好不要省略文件状态变量

UML图:


文件打开操作

int LoLogs::OpenLog(const char *pcLogLead)
{
	int nRet = 0;

	if(m_nFileStatus == FILESTATUS_CLOSE)
	{
		char szOpenPathName[MAXSIZE_PATHNAME] = {0};

		time_t	ltime;
		tm		tmStruct;
		time(<ime);
		tmStruct = *localtime(<ime);

		strcat(szOpenPathName, SUBDIRNAME_LOG);
		sprintf(szOpenPathName + strlen(szOpenPathName), "%s%04d-%02d-%02d.log",pcLogLead, tmStruct.tm_year+1900,tmStruct.tm_mon+1,tmStruct.tm_mday);
		#ifdef WIN32
		CreateDirectory(SUBDIRNAME_LOG, NULL);
		#else /* LINUX */
		mkdir(SUBDIRNAME_LOG, 0700);
		#endif
		m_fileSvrLog = fopen(szOpenPathName, "a+");
		if(m_fileSvrLog) 
		{
			m_nFileStatus = FILESTATUS_OPEN;
		}
		else
		{
			nRet = -1;
		}
	}

	return nRet;
}

获取当前时间的字符串

// CLogs class member functions
const char *LoLogs::GetCurDateTimeWithString(char *pStringBuf)
{
	time_t	tCurDateTime;
	tm		*ptagCurDataTime;
	char	szTimeStringBuf[MAXSIZE_TIMESTRING] = {0};

	char *pWriteStringBuf = pStringBuf;
	if(NULL == pWriteStringBuf)
	{
		pWriteStringBuf = szTimeStringBuf;
	}

	time(&tCurDateTime);
	ptagCurDataTime = localtime(&tCurDateTime);

	sprintf(pWriteStringBuf, "%d-%02d-%02d %02d:%02d:%02d", 
		ptagCurDataTime->tm_year+1900, 
		ptagCurDataTime->tm_mon+1, 
		ptagCurDataTime->tm_mday, 
		ptagCurDataTime->tm_hour, 
		ptagCurDataTime->tm_min, 
		ptagCurDataTime->tm_sec);

	return pWriteStringBuf;
}

变参函数的处理

void LoLogs::WriteLog(const char *pcLogMsg, ...)
{
	char szMsgBuf[MAXSIZE_MSGBUF] = {0};
	va_list va;
	va_start(va, pcLogMsg);
	vsprintf(szMsgBuf, pcLogMsg, va);
#ifdef WIN32
	printf( szMsgBuf );
#endif
	va_end(va);
	WriteLogInner(szMsgBuf, LOGLEADNAME_BOOT);
}

c++实现日志系统源码


Logo

更多推荐