上一篇 | 下一篇

CLog一个用于记录日志的类

发布: 2008-6-26 13:40 | 作者: admin | 来源: | 查看: 4次

下载本文所附源代码

#ifndef _LOG_H

#define _LOG_H

class CLog

{

public:

CLog();

~CLog();

public:

void InitLog(LPCTSTR lpszLogPath);

void Add(const char* fmt, ...); //输出文字,参数就跟printf一样

protected:

enum {BUFSIZE = 3000}; //工作缓冲区

char m_tBuf[BUFSIZE];

CString m_strLogPath;

CR99vICAL_SECTION m_crit; //设置一个临界区

};

#endif

#include "stdafx.h"

#include "log.h"

CLog::CLog() //构造函数,设置日志文件的默认路径

{

::InitializeCriticalSection(&m_crit); //初始化临界区

}

CLog::~CLog()

{

::DeleteCriticalSection(&m_crit); //释放里临界区

}

/*================================================================

* 函数名: InitLog

* 参数: LPCTST lpszLogPath

* 功能描述: 初始化日志(设置日志文件的路径)

* 返回值: void

* 作 者: 程红秀 2005年01月06日

================================================================*/

void CLog::InitLog(LPCTSTR lpszLogPath)

{

m_strLogPath=lpszLogPath;

}

void CLog::Add(const char* fmt, ...)

{

if (m_strLogPath.IsEmpty())

return ;

if (!AfxIsValidString(fmt, -1))

return ;

/*-----------------------进入临界区(写文件)------------------------------------*/

::EnterCriticalSection(&m_crit);

try

{

va_list argptr; //分析字符串的格式

va_start(argptr, fmt);

_vsnprintf(m_tBuf, BUFSIZE, fmt, argptr);

va_end(argptr);

}

catch (...)

{

m_tBuf[0] = 0;

}

FILE *fp = fopen(m_strLogPath, "a"); //以添加的方式输出到文件

if (fp)

{

fprintf(fp,"%s: ", AfxGetApp()->m_pszExeName); //加入当前程序名

CTime ct ; //加入当前时间

ct = CTime::GetCurrentTime();

fprintf(fp,"%s : ",ct.Format("%m/%d/%Y %H:%M:%S"));

fprintf(fp, "%s\n", m_tBuf);

fclose(fp);

}

::LeaveCriticalSection(&m_crit);

/*-------------------退出临界区----------------------------------------*/

}

字号: | 推荐给好友

21/212>

评分:0

我来说两句