VC++ 一个简单的Log类

  在软件开发中,为程序建立Log日志是很必要的,它可以记录程序运行的状态以及出错信息,方便维护和调试。

  下面实现了一个简单的Log类,使用非常简单,仅供参考。

 // CLogHelper.h : header file for log information
 //

 #pragma once

 class CLogHelper
 {
 public:
     CLogHelper(void);
     ~CLogHelper(void);
     static void WriteLog(LPCTSTR lpszLog);

 private:
     static CString MakeFilePath();
     static CString MakeLogMsg(LPCTSTR lpszLog);
 };

    

// LogHelper.cpp : implementation file
//

#include "StdAfx.h"
#include "LogHelper.h"
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
#include <locale>

#define LOG_FILE_NAME     _T("*Log.log")

CLogHelper::CLogHelper(void)
{
}

CLogHelper::~CLogHelper(void)
{
}

void CLogHelper::WriteLog( LPCTSTR lpszLog )
{
    // 获取日志文件路径
    static CString strLogFilePath = _T("");
    if (strLogFilePath.IsEmpty())
    {
        strLogFilePath = MakeFilePath();
    }
    // 判断日志文件是否存在,不存在则创建
    wchar_t* pwchLogFilePath = strLogFilePath.AllocSysString();
    errno_t err = 0;
    if ((err = _taccess_s(pwchLogFilePath, 0)) != 0)
    {
        CStdioFile file;
        if(file.Open(strLogFilePath, CStdioFile::modeCreate))
        {
            file.Close();
        }
    }
    // 向日志文件写入日志
    CStdioFile file;
    if (file.Open((LPCTSTR)strLogFilePath, CStdioFile::modeWrite | CStdioFile::shareDenyNone))
    {
        CString strMsg = MakeLogMsg(lpszLog);
        file.SeekToEnd();
        char* old_locale = _strdup( setlocale(LC_CTYPE,NULL) );
        setlocale( LC_CTYPE, "chs" );  // 设定区域
        file.WriteString(strMsg);
        setlocale( LC_CTYPE, old_locale );
        free( old_locale );        // 还原区域设定
        file.Close();
    }

}

CString CLogHelper::MakeLogMsg(LPCTSTR lpszLog)
{
    CTime time = CTime::GetCurrentTime();
    CString strMsg = time.Format("[%Y-%m-%d %H:%M:%S] ");
    strMsg = strMsg + lpszLog + _T("
");
    return strMsg;
}

CString CLogHelper::MakeFilePath()
{
    // 获取当前进程路径
    TCHAR szFilePath[MAX_PATH];
    memset(szFilePath, 0, MAX_PATH);
    ::GetModuleFileName(NULL, szFilePath, MAX_PATH);

    (_tcsrchr(szFilePath, _T('\')))[1] = 0;      // 删除文件名,只获得路径字符串
    CString strFilePath = szFilePath;
    strFilePath = strFilePath + LOG_FILE_NAME;

    return strFilePath;
}

  使用方法: 

CString strLogMsg = _T("程序开始运行...");
CLogHelper::WriteLog(strLogMsg);
原文地址:https://www.cnblogs.com/MakeView660/p/6108548.html