VC++日志类(CLogFile)

功能说明:
此类可以实现大多数应用程序日志功能,可以每天创建一个Log文件,支持中文内容。

调用方法:
1、首先在要调用的页面加入引用:#include “LogFile.h”
2、然后,写入下列代码可以正常调用:CLogFile::WriteLog(“IO错误,文件打开失败!”);

程序代码:
LogFile.h头文件

// LogFile.h: interface for the CLogFile class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_LOGFILE_H__6B67A565_13A5_4A20_9C35_3F4FDD9057C3__INCLUDED_)
#define AFX_LOGFILE_H__6B67A565_13A5_4A20_9C35_3F4FDD9057C3__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

class CLogFile  
{
public:
	CLogFile();
	virtual ~CLogFile();
	static CString GetFileName();
    static CString GetFilePath();
    static BOOL WriteLog(CString LogText);
};

#endif // !defined(AFX_LOGFILE_H__6B67A565_13A5_4A20_9C35_3F4FDD9057C3__INCLUDED_)

LogFile.cpp文件

// LogFile.cpp: implementation of the CLogFile class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "lineprotection.h"
#include "LogFile.h"

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

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CLogFile::CLogFile()
{

}

CLogFile::~CLogFile()
{

}
//获取文件名称
CString CLogFile::GetFileName()
{
	CString m_sFileName;
    m_sFileName = CTime::GetCurrentTime().Format("%Y-%m-%d") + ".log";

	return m_sFileName;
}
//获取应用程序所在路径
CString CLogFile::GetFilePath()
{   
	CString m_FilePath;
    GetModuleFileName(NULL,m_FilePath.GetBufferSetLength(MAX_PATH+1),MAX_PATH);
    m_FilePath.ReleaseBuffer();
    int m_iPosIndex;
    m_iPosIndex = m_FilePath.ReverseFind('\\'); 
    m_FilePath = m_FilePath.Left(m_iPosIndex) + "\\Log";
    return m_FilePath;
}
BOOL CLogFile::WriteLog(CString LogText)
{
	try
	{
		CFile m_File;
		CStdioFile m_SFile;
		CFileFind m_FileFind;
		CString m_sErrorMessage;
		CString m_sFileName = GetFileName();
		CString m_sFilePath = GetFilePath();
		CString m_sCurrentTime = CTime::GetCurrentTime().Format("%Y-%m-%d %X");

		m_sErrorMessage = "[" + m_sCurrentTime + "]" + "\t";
		m_sErrorMessage += LogText + "\r";
        if(!m_FileFind.FindFile(m_sFilePath))
		{
			CreateDirectory(m_sFilePath,NULL);
		}

		if(!m_SFile.Open(m_sFilePath + "\\" +m_sFileName,CFile::modeReadWrite))
		{
			m_SFile.Open(m_sFilePath + "\\" + m_sFileName,
				CFile::modeCreate | CFile::modeReadWrite | CFile::typeText);
		}

		m_SFile.SeekToEnd(); 
        char* m_szMessage;
        m_szMessage=(LPTSTR)(LPCTSTR)m_sErrorMessage;
        m_SFile.Write(m_szMessage,lstrlen(m_szMessage));   
        m_SFile.Close();
	}
	catch(CFileException fileException)
	{
		return false;
	}
    return true;
}


发表评论

邮箱地址不会被公开。