关于编写日志文件笔记

/******************************************************************************
 * Log.h 
 * 
 * Copyright: Suzhou Atlight Technology Co.,Ltd. All rights reserved
 * 
 * DESCRIPTION: 
 * 
 * modification history
 * --------------------
 * v1.0   2012/02/16, yeyn create this file
 * 
 ******************************************************************************/

#ifndef __LOG_H__
#define __LOG_H__

#include "FIFO.h"
#include <IOSTREAM>
#include <string>
using namespace std;

typedef enum UNI_ERR_CODE
{
	ERR_OK=0,
	ERR_TIME_OUT,
	ERR_PARA,
	ERR_MEM,
	ERR_FILE,
	ERR_SYS,
	ERR_COMM,
	ERR_NET,
	ERR_STATE,
	ERR_DISK,
	ERR_CARD,
	ERR_DEV,
};

typedef enum
{
	LOG_DEBUG=0,
	LOG_INFO,
	LOG_NOTICE,
	LOG_WARNING,
	LOG_ERROR,
	LOG_CRITICAL,
	LOG_EMERGENCY,
};


class CLogFunc
{
private:
	string	m_file;
	int		m_line;

public:
	CLogFunc(const char *file, const int line);
	void ClogMessage(const int logLevel, const char* format, ... );
};

#define CLogMessage		CLogFunc(__FILE__, __LINE__).ClogMessage

int CreateMultiDir(char* szPath);
void loggerInit(int leve=LOG_DEBUG);
void loggerUnInit();


#endif //__LOG_H__
/******************************************************************************
 * Log.cpp 
 * 
 * Copyright: Suzhou Atlight Technology Co.,Ltd. All rights reserved
 * 
 * DESCRIPTION: 
 * 
 * modification history
 * --------------------
 * v1.0   2012/02/16, yeyn create this file
 * 
 ******************************************************************************/

#include "stdafx.h"
#include <time.h>
#include <io.h>
#include <direct.h>
#include "CLog.h"


#define  MAX_FILEPATH_LEN	520

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif


static string dayTime;
static FIFO<string> logBuff;
static HANDLE LoggerThread;
static int gLogLevel;

static bool exitEvt;

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

const char* logLevelMsg [] = 
{
	"DEBUG",
	"INFO",
	"NOTICE",
	"WARNING",
	"ERROR",
	"CRITICAL",
	"EMERGENCY",
};

/************************************************************************/
/*                                                                      */
/************************************************************************/
int CreateMultiDir(char* szPath)
{
	int k = 0;
	char szFilePath[MAX_PATH];
	char szBuf[MAX_PATH];
	strcpy(szBuf, szPath);
	int i = strlen(szBuf);

	for (int j=0; j<i; j++)
	{
		if (szBuf[j] == '\\' || szBuf[j] == '/')
		{
			// 解出一级目录
			k = j;
			strncpy(szFilePath, szBuf, k);
			szFilePath[k] = '\0';

			if ((_access(szFilePath, 0)) == -1)
				// 创建目录
				if (mkdir(szFilePath) == -1)
					return -1;
		}
	}

	if (k == 0) // 非法目录
		return -1;

	return 0;
}


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

CLogFunc:: CLogFunc(const char *file, const int line)
{
	m_file.assign(file);
	m_line = m_file.find_last_of('\\');
	if (m_line != string::npos)
	{
		m_line++;
	}
	else
	{
		m_line = 0;
	}

	m_file = m_file.substr(m_line);
	m_line = line;
}


void CLogFunc:: ClogMessage(const int logLevel, const char* format, ... )
{
	if ((logLevel < LOG_DEBUG)||(logLevel > LOG_EMERGENCY))
		return;
	if (logLevel < gLogLevel)
		return;

	const char* levmsg = logLevelMsg[logLevel];
	int t=0;
	char out[4096] = {0};
	char fmt[512] = {0};
	va_list ap;

	time_t nowTime = time(NULL);
	tm tmNow = *localtime(&nowTime);
	strftime(fmt, 512, "[%Y-%m-%d %H:%M:%S]", &tmNow);
	_snprintf(fmt, 512, "%s [%s] [%s]-[%d] - ", fmt, levmsg, m_file.c_str(), m_line);
	strcat(fmt, format);

	va_start(ap, format);
	t = _vsnprintf(out, 4096, fmt, ap);
	va_end(ap);

	//AfxMessageBox(out);
	logBuff.push(string(out));
}


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

DWORD CALLBACK LoggerHandler(LPVOID argv)
{
	string logmsg;
	time_t nowTime = time(NULL);
	time_t delTime = time(NULL);
	tm tmNow, tmDel, tmTemp;

	char szLogFilePath[MAX_PATH] = {0};
	char szDelLogFile[MAX_PATH] = {0};
	char szLogFile[MAX_PATH] = {0};
	char szNowTime[MAX_PATH] = {0};
	char szDelTime[MAX_PATH] = {0};

	FILE *mfile = NULL;

	GetModuleFileName(NULL, szLogFilePath, MAX_PATH);
	int len=strlen(szLogFilePath);

	while (len > 0)
	{
		len--;
		if (szLogFilePath[len] == '\\')
			break;
	}

	if (len > 0)
		szLogFilePath[len] = 0;
	else
		GetCurrentDirectory(MAX_PATH, szLogFilePath);

	if (szLogFilePath[0] != '\\')
		strcat(szLogFilePath, "\\");
	strcat(szLogFilePath, "log\\");
	strcat(szLogFilePath, AfxGetApp()->m_pszExeName);
	strcat(szLogFilePath, "\\");
	CreateMultiDir(szLogFilePath);

	tmNow = *localtime(&nowTime);
	strftime(szNowTime, MAX_PATH, "%Y%m%d", &tmNow);
	sprintf(szLogFile, "%s%s.log", szLogFilePath, szNowTime);
	dayTime.assign(szNowTime);

	try
	{
		mfile = fopen(szLogFile, "a+");
	}
	catch (...)
	{
		TRACE("Failed To Open Log File !");
		return ERR_FILE;
	}

	while (true)
	{
		if (exitEvt)
			break;

		logmsg.erase();
		if ((!logBuff.pop(logmsg))||(logmsg.empty()))
		{
			Sleep(1);
			continue;
		}

		nowTime = time(NULL);
		tmNow = *localtime(&nowTime);
		strftime(szNowTime, MAX_PATH, "%Y%m%d", &tmNow);

		if (dayTime.compare(szNowTime) != 0)
		{
			dayTime.assign(szNowTime);
			tmTemp = *localtime(&nowTime);
			tmTemp.tm_mday -= 30;			//30days
			delTime = mktime(&tmTemp);

			tmDel = *localtime(&delTime);
			strftime(szDelTime, MAX_PATH, "%Y%m%d", &tmDel);

			sprintf(szLogFile,    "%s%s.log", szLogFilePath, szNowTime);
			sprintf(szDelLogFile, "%s%s.log", szLogFilePath, szDelTime);
			DeleteFile(szDelLogFile);

			if (mfile != NULL)
			{
				try
				{
					fclose(mfile);
					mfile = fopen(szLogFile, "a+");
				}
				catch (...)
				{
					TRACE("Failed To Open Log File for write !");
					//return ERR_FILE;
					continue;
				}
			}
		}

		try
		{
			if (mfile == NULL)
			{
				try
				{
					mfile = fopen(szLogFile, "a+");
				}
				catch (...)
				{
					TRACE("Failed to Open log file !");
					//return ERR_FILE;
					continue;
				}
			}
			fwrite(logmsg.c_str(), sizeof(char), logmsg.length(), mfile);
			fflush(mfile);
		}
		catch (...)
		{
			//TRACE("Failed to write log message !");//AfxMessageBox("Failed to write log message !");
		}
	}

	fclose(mfile);
	mfile = NULL;

	return 0;
}


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

void loggerUnInit()
{
	exitEvt = true;
	if (LoggerThread != NULL)
	{
		WaitForSingleObject(LoggerThread, INFINITE);
		CloseHandle(LoggerThread);
	}
}

void loggerInit(int leve)
{
	if (LoggerThread != NULL)
	{
		exitEvt = true;
		WaitForSingleObject(LoggerThread, INFINITE);
	}

	exitEvt = false;
	gLogLevel = leve;
	LoggerThread = CreateThread(NULL, 0, LoggerHandler, NULL, 0, NULL);
}


/// End Of File

/******************************************************************************
 * FIFO.h 
 * 
 * Copyright: Suzhou Atlight Technology Co.,Ltd. All rights reserved
 * 
 * DESCRIPTION: 
 * 
 * modification history
 * --------------------
 * v1.0   2011/12/23
 * 
 ******************************************************************************/

#ifndef __FIFO_H__
#define __FIFO_H__

#include <afxmt.h>
#include <deque>

//#include "mscomm.h"

using namespace std;


/*==============================================================*/
/* Template  FIFO */
/*==============================================================*/
template<class TYPE>
class FIFO
{
private:
	unsigned int     MAX_SIZE;
	deque<TYPE>	     myDeque;
	CCriticalSection section;
	CSemaphore		 *occupied;
	CSemaphore		 *emptied;

public:
	FIFO (unsigned int maxSize = 1024)
	{
		MAX_SIZE = maxSize;
		myDeque.resize(MAX_SIZE);
		myDeque.clear();
		occupied = new CSemaphore(0, MAX_SIZE);
		emptied  = new CSemaphore(MAX_SIZE, MAX_SIZE);
	}
	~FIFO ()
	{
		if (occupied)
			delete occupied;
		if (emptied)
			delete emptied;
	}

public:
	inline bool empty()
	{
		return myDeque.empty();
	}
	inline int size()
	{
		return myDeque.size();
	}

	bool push(TYPE &pIpc)
	{
		WaitForSingleObject(emptied->m_hObject, INFINITE);

		section.Lock();
		myDeque.push_back(pIpc);
		section.Unlock();

		ReleaseSemaphore(occupied->m_hObject, 1, NULL);

		return true;
	}

	bool pop(TYPE &pIpc)
	{
		if (myDeque.empty())
			return false;

		WaitForSingleObject(occupied->m_hObject, INFINITE);

		section.Lock();
		pIpc = myDeque.front();
		myDeque.pop_front();
		section.Unlock();

		ReleaseSemaphore(emptied->m_hObject, 1, NULL);

		return true;
	}
};


#endif //__FIFO_H__
//end of the file 
注:一定记得要在BOOL CMSComDlg::OnInitDialog()添加loggerInit(LOG_DEBUG);初始化函数
CLogMessage(LOG_DEBUG, "雷达速度:[%d] mm/s !\n",tmpSpeed);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值