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

📄 logfile.cpp

📁 ABis无线接口全套资料
💻 CPP
字号:
/* ======================================================================== *\
 |
 |
 |  JOYIT Communication Technology
 |  Copyright (C)  2003-2006,  All Right Reserved.
 |
 |  System: Programmable Signaling Gateway
 |  Sub-system:
 |  Filename: logfile.cpp
 |  Environment:    LINUX -- Red Hat 7.2 & GNU C/C++ Compiler 2.96
 |                vxWorks -- Tornado 2.0 & vxWorks 5.4
 |  Function description: Define the the function of general log file
 |           management or my system.
 |
\* ======================================================================== */

#ifndef _LOGFILE_HPP
#include "logfile.hpp"
#endif

/*
#ifndef _WERROR_HPP
#include "werror.hpp"
#endif
*/

#ifndef __TEST__
#ifndef _EXCEPTION_HPP
#include "exception.hpp"
#endif
#endif // ifndef __TEST__


#ifndef _OBJECTS_HPP
#include "objects.hpp"
#endif


extern "C"
{
#ifndef _STRING_H
#include <string.h>
#endif

#ifndef _TIME_H
#include <time.h>
#endif

#ifndef _SYS_TYPES_H
#include <sys/types.h>
#endif

#ifndef _SYS_STAT_H
#include <sys/stat.h>
#endif

#ifndef _UNISTD_H
#include <unistd.h>
#endif
};

LogFile::LogFile( ) : fp(NULL), iBuffer(NULL), bufLength(BUF_LEN), lenLimit(0),
						fnMode(FILENAME), seqNo(0), lineCount(0), totalFileLength(0L)
{
	iBuffer = new char *[BUF_LEN];
	if (NULL == iBuffer)
	{
		return;
	}

	for (int i=0; i<bufLength; i++)
	{
		iBuffer[i] = new char [MAX_STRLEN];
		if (NULL == iBuffer[i])
		{
			for (int j=0; j<i; j++)
			{
				delete iBuffer[j];
			}
			delete iBuffer;
			iBuffer = NULL;
		}
	}

	fnPrefix[0] = '\0';
	fnSuffix[0] = '\0';
	filename[0] = '\0';

	// ### Add 2006-06-02, by Wu jianjin
	lenLimit = 256L*1024L-bufLength; // Maxinum length of file size in LINXU OS
	// ### End 2006-06-02 ###
}

LogFile::~LogFile( )
{
	Flush( );
	CloseFile( );
	if (iBuffer != NULL)
	{
		for (int i=0; i<bufLength; i++)
		{ // releae the buffer memory
			if (iBuffer[i] != NULL)
			{
				delete iBuffer[i];
			}
		}
		delete iBuffer;
		iBuffer = NULL;
	}

}

void LogFile::Init(const char * const pre, const char * const suf, INT8 fm)
{
	if ((NULL == pre)  ||
		(NULL == suf))
	{
		return;
	}

	if (strlen(pre) >= MAX_PREFIX  ||  strlen(suf) >= MAX_SUFFIX  ||  fm < 0)
	{
		return;
	}
	else
	{
		memset(fnPrefix, 0, MAX_PREFIX);
		memset(fnSuffix, 0, MAX_SUFFIX);

		memcpy(fnPrefix, pre, strlen(pre));
		memcpy(fnSuffix, suf, strlen(suf));

		fnMode = fm;
	}
}

void LogFile::SetFileName(const char * const fn)
{
	if (NULL == fn)
	{
		return;
	}

	if (strlen(fn) >= MAX_FILENAME)
	{
		return;
	}
	else
	{
		memset(filename, 0, MAX_FILENAME);
		memcpy(filename, fn, strlen(fn));
		fnMode = FILENAME;
		if (fp != NULL)
		{ // If there has file been opened, then close it first.
			CloseFile( );
		}
	}
}

void LogFile::SetBufLength(int bl)
{
	if ((bl > 0)  &&  (bl < MAX_BUF_LEN))
	{
		Flush( );

		int i, j;

		if (bl < bufLength)
		{
			char  ** ib;
			ib = new char *[bl];
			if (ib != NULL)
			{
				for (i=0; i<bl; i++)
				{
					ib[i] = iBuffer[i];
				}

				for (i=bl; i<bufLength; i++)
				{
					if (iBuffer[i] != NULL)
					{
						delete iBuffer[i];
						iBuffer[i] = NULL;
					}
				}

				bufLength = bl;
				if (iBuffer != NULL)
				{
					delete iBuffer;
				}
				iBuffer = ib;
			}
		}
		else if (bl > bufLength)
		{
			char  ** ib;
			ib = new char *[bl];
			if (ib != NULL)
			{
				for (i=bufLength; i<bl; i++)
				{
					ib[i] = new char [MAX_STRLEN];
					if (NULL == ib[i])
					{
						for (j=bufLength; j<i; j++)
						{
							delete ib[j];
						}

						delete ib;
						return; // Out of memory, ignore this requst.
					}
				}

				for (i=0; i<bufLength; i++)
				{
					ib[i] = iBuffer[i];
				}

				bufLength = bl;
				if (iBuffer != NULL)
				{
					delete iBuffer;
				}
				iBuffer = ib;
			}
		}
	}
}

void LogFile::SetLengthLimit(UINT32 ll)
{
	if (ll <= 256L*1024L)
	{
		lenLimit = ll - bufLength;

		if (lenLimit > (UINT32)(256L*1024L - bufLength))
		{
			lenLimit = bufLength;
		}
	}
}

ERRCOD_T LogFile::OpenFile( )
{
	CreateFileName( );
	// ### Add 2006-06-05, by Wu jianjin.
	/*struct stat  * statbuf;
	int r;
	r=stat(filename, statbuf);
	if (0 == r)
	{
		totalFileLength = statbuf->st_size;
	}*/
	// ### End ###


	if (filename[0] != '\0')
	{
		fp = fopen(filename, "a"); // Open the file with append mode, if the file no exist, it will be created.
		if (NULL == fp)
		{ // File open failed, exception handle.
			#ifndef __TEST__
			if (NULL != xcpPtr)
			{
				xcpPtr->error(E_FILE_OPEN_FAILED, SF_LOGFILE, filename);
			}
			#endif // ifndef __TEST__

			return E_FILE_OPEN_FAILED;
		}
		else
		{
			totalFileLength = ftell(fp);
			if (totalFileLength < 0L)
			{
				totalFileLength = 0L;
			}

			return E_SUCC;
		}
	}
	else
	{
		#ifndef __TEST__
		if (NULL != xcpPtr)
		{
			xcpPtr->error(E_FILE_NAME_NULL, SF_LOGFILE, filename);
		}
		#endif // ifndef __TEST__

		return E_FILE_NAME_NULL;
	}
}

ERRCOD_T LogFile::ReOpenFile( )
{
	ERRCOD_T errcod;

	// errcod = CloseFile( ); // Delete 2006-06-02, by Wu jianjin.
	if (fp != NULL)
	{
		fclose(fp); // Add 2006-06-02, by Wu jianjin.
		fp = NULL; // Add 2006-06-02, by Wu jianjin.
	}

	errcod = E_SUCC; // Add 2006-06-02, by Wu jianjin.

	if (errcod == E_SUCC)
	{
		CreateFileName( );

		if (filename[0] != '\0')
		{
			fp = fopen(filename, "a+"); // Open the file with append mode, if the file no exist, it will be created.
			if (NULL == fp)
			{ // File open failed, exception handle.
				#ifndef __TEST__
				if (NULL != xcpPtr)
				{
					xcpPtr->error(E_FILE_OPEN_FAILED, SF_LOGFILE, filename);
				}
				#endif // ifndef __TEST__

				return E_FILE_OPEN_FAILED;
			}
			else
				return E_SUCC;
		 }
		else
		{
			#ifndef __TEST__
			if (NULL != xcpPtr)
			{
				xcpPtr->error(E_FILE_NAME_NULL, SF_LOGFILE, filename);
			}
			#endif // ifndef __TEST__

			return E_FILE_NAME_NULL;
		}
	}
	else
		return errcod;
}

ERRCOD_T LogFile::CloseFile( )
{
	if (NULL == fp)
		return E_SUCC;

	Flush( );

	int r;
	r = fclose(fp);
	if (r == EOF)
	{
		#ifndef __TEST__
		if (NULL != xcpPtr)
		{
			xcpPtr->error(E_FILE_CLOSE_FAILED, SF_LOGFILE, filename);
		}
		#endif // ifndef __TEST__

		r = E_FILE_CLOSE_FAILED;
	}
	else
	{
		r = E_SUCC;
	}

	fp = NULL;

	return r;
}

void LogFile::Flush( )
{
	// If the file size exceed the limited.
	if (lenLimit)
	{
		if ((totalFileLength/1024+1) >= lenLimit)
		{
			// Add 2006-06-02, by Wu jianjin.
			if (FILENAME == fnMode)
			{
				MovingOldLogFile( );
			}

			ReOpenFile( );
			totalFileLength = 0L;
		}
		else
		{
			Write2File( );
		}
	}
	else
	{
		Write2File( );
	}

	/*
		int fd;

		fd = fileno(fp);
		if (fd != -1)
		{
			struct stat  * statbuf;
			int r;
			r=fstat(fd, statbuf);
			if (r != -1)
			{
				if (((UINT32)(statbuf->st_size/1024)) > lenLimit)
				{
					// Add 2006-06-02, by Wu jianjin.
					if (FILENAME == fnMode)
					{
						MovingOldLogFile( );
					}

					ReOpenFile( );
				}
				// else
				// { // Write data into file.
					Write2File( );
				// }
			}
			else
			{ // Discard current data in buffers.
				ClearBuffer( );
			}
		}
		else
		{ // Discard current data in bufers.
			ClearBuffer( );
		}
	}
	else
	{ // if lenLimit==0, no limit.
		Write2File( );
	}*/
}

void LogFile::Log(const char * const msg)
{
	if ((NULL == msg)  ||
		(NULL == iBuffer))
	{
		return;
	}

	if (lineCount >= bufLength)
	{
		Flush( );
		lineCount = 0;
	}

	if (iBuffer[lineCount] != NULL)
	{

		int len = strlen(msg);

		if (len >= (MAX_STRLEN-1))
		{
			len = MAX_STRLEN - 1 - 1;
		}

		// memset(iBuffer[lineCount], 0, MAX_STRLEN);
		memcpy(iBuffer[lineCount], msg, len);
		iBuffer[lineCount][len] = '\0';
		++lineCount;

		totalFileLength += (len+1); // Add 2006-06-05, by Wu jianjin.
	}
}

void LogFile::CreateFileName( )
{
	time_t currentTime;
	struct tm  * lct;

	switch (fnMode)
	{
		case FILENAME:
			break; // File name already in filename[].

		case YMD_SUF:
			currentTime = time(NULL);
			lct = localtime(&currentTime);
			sprintf(filename, "%04d%02d%02d.%s", lct->tm_year+1900, lct->tm_mon+1, lct->tm_mday, fnSuffix);
			break;

		case PRE_YMD:
			currentTime = time(NULL);
			lct = localtime(&currentTime);
			sprintf(filename, "%s%04d%02d%02d", fnPrefix, lct->tm_year+1900, lct->tm_mon+1, lct->tm_mday);
			break;

		case PRE_YMD_SUF:
			currentTime = time(NULL);
			lct = localtime(&currentTime);
			sprintf(filename, "%s%04d%02d%02d.%s", fnPrefix, lct->tm_year+1900, lct->tm_mon+1, lct->tm_mday, fnSuffix);
			break;

		case PRE_SUF:
			sprintf(filename, "%s.%s", fnPrefix, fnSuffix);
			break;

		case PRE_SEQ:
			sprintf(filename, "%s.%04d", fnPrefix, seqNo++);
			// seqNo ++;
			break;

		case PRE_SEQ_SUF:
			sprintf(filename, "%s%04d.%s", fnPrefix, seqNo++, fnSuffix);
			break;

		case SEQ_SUF:
			sprintf(filename, "%04d.%s", seqNo++, fnSuffix);
			break;

		default:
			break;
	} // End of switch(fnMode)
}

// ### Add 2006-06-02, by Wu jianjin.
void LogFile::MovingOldLogFile( ) // Only for fnMode = FILENAME
{
	fclose(fp);
	fp = NULL;

	char tempDir[1024];
	char tempPn[1024];

	char  * p = getcwd(tempDir, 1024);

	if (NULL == p)
	{ // Exception handle.
		return;
	}

	if ((strlen(tempDir)+strlen(filename)+2) >= 1024)
	{ // Exception handle.
		return;
	}

	char tempSuffix[16];
	char sn = 4;

	// Remove the oldest logging file.
	sprintf(tempSuffix, ".%d", sn);
	strcpy(tempPn, tempDir);
	strcat(tempPn, "/");
	strcat(tempPn, filename);
	strcat(tempPn, tempSuffix);
	remove(tempPn);

	// Rename all previous logging files.
	char tempOldName[1024];
	for (char i=sn; i>0; i--)
	{
		strcpy(tempPn, tempDir);
		strcat(tempPn, "/");
		strcat(tempPn, filename);

		strcpy(tempOldName, tempPn);

		sprintf(tempSuffix, ".%d", i);
		strcat(tempPn, tempSuffix);

		sprintf(tempSuffix, ".%d", i-1);
		strcat(tempOldName, tempSuffix);

		rename(tempOldName, tempPn);
	}

	// Moving current log file to .0
	strcpy(tempPn, tempDir);
	strcat(tempPn, "/");
	strcat(tempPn, filename);
	strcpy(tempOldName, tempPn);
	sprintf(tempSuffix, ".%d", 0);
	strcat(tempPn, tempSuffix);
	rename(tempOldName, tempPn);
}

void LogFile::Write2File( )
{
	if (NULL == fp)
		return;

	for (int i=0; i<lineCount; i++)
	{
		strcat(iBuffer[i], "\n");
		if (fputs(iBuffer[i], fp) == EOF)
		// fputs(iBuffer[i], fp);
		// if (fputs("\n", fp) == EOF)
		{   // Write to file error.
			#ifndef __TEST__
			if (NULL != xcpPtr)
			{
				xcpPtr->error(E_FILE_WRITE_ERROR, SF_LOGFILE, filename);
			}
			#endif // ifndef __TEST__

			// CloseFile( );
			fclose(fp);
			fp = NULL;
		}
		//else
		//{
		//	fflush(fp);
		// }
	}

	if (fp != NULL)
	{
		fflush(fp);
	}

	lineCount = 0;
}

void LogFile::ClearBuffer( )
{
	lineCount = 0;
}

// ### End 2006-06-02 ###

// ------------------------------------------------------------------------
//
//  Revision list.
//  ==============
//
//  1.0,        2003-04-18,     Wu jianjin
//      Initial version.
//  1.1,        2003-05-19,     Wu jianjin
//      Ported to vxWorks.
//	2.0,		2006-06-02,		Wu jianjin
//		Adding auto remove oldest logging file.
//		Size of log file is 2GB, and will reserved 10 log files.
//	2.1			2006-07-03,		Wu jianjin
//		Size of log file is 256MB, and will reserved 5 log files.
//
// ------------------------------------------------------------------------

⌨️ 快捷键说明

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