一个写日志的类

来源:互联网 发布:雷查尔斯 知乎 编辑:程序博客网 时间:2024/04/29 23:35

使用方法,创建一个CMyLog的对象,调用WriteLog函数,即可进行日志记录工作

头文件

#pragma once

class CMyLog
{
public:
 CMyLog(void);
 ~CMyLog(void);
 // 默认的日志文件路径
private:
 CString m_strLogPath;
 // 获得日志文件路进
 void GetLogPath(void);
public:
 void WriteLog(CString LogInfo, CString strLogFilePath = NULL);
};

实现文件

#include "StdAfx.h"
#include "./mylog.h"
const unsigned int PATH_LENGTH = 512;

CMyLog::CMyLog(void)
: m_strLogPath(_T(""))
{
 GetLogPath();
}

CMyLog::~CMyLog(void)
{
}

// 获得日志文件路进
void CMyLog::GetLogPath(void)
{
 TCHAR path[PATH_LENGTH] = {0};
 HMODULE hModule = ::GetModuleHandle(NULL);
 int length = ::GetModuleFileName(hModule,path,sizeof(path)/sizeof(TCHAR));
    m_strLogPath = path;
 int Index = m_strLogPath.ReverseFind('//');
 m_strLogPath = m_strLogPath.Left(Index);
 Index = m_strLogPath.ReverseFind('//');
 m_strLogPath = m_strLogPath.Left(Index);
 m_strLogPath += "//Log";
 CFileFind fileFind;
 if(fileFind.FindFile(m_strLogPath)== 0)
 {
  ::CreateDirectory(m_strLogPath,NULL);
 }
 m_strLogPath = m_strLogPath + "//log.txt";
}

void CMyLog::WriteLog(const CString LogInfo, const CString strLogFilePath)
{
 CStdioFile file;
 CString strLogInfo;
 CTime time = CTime::GetCurrentTime();
 strLogInfo.Format("%04d-%02d-%02d %02d:%02d:%02d  ---  ",time.GetYear(),time.GetMonth(),time.GetDay(),time.GetHour(),time.GetMinute(),time.GetSecond());
 if(strLogFilePath.IsEmpty())
 {
  file.Open(m_strLogPath,CStdioFile::modeNoTruncate|CStdioFile::modeCreate|CStdioFile::modeReadWrite|CStdioFile::shareDenyWrite);  
 }
 else
 {
  file.Open(strLogFilePath,CStdioFile::modeNoTruncate|CStdioFile::modeCreate|CStdioFile::modeReadWrite|CStdioFile::shareDenyWrite);
 }
 strLogInfo = "/r/n" + strLogInfo + LogInfo;
 file.SeekToEnd();
 file.WriteString(strLogInfo);
 file.Close();
}
 

原创粉丝点击