C++日志类

//Log.h头文件
/*
简单日志类  
*/
#ifndef LOGGER_H_
#define LOGGER_H_
#include <string>
#include <time.h>
#include <Windows.h>
using namespace std;
//日志级别枚举  
typedef enum LogLevel  
{  
	信息 = 0,  //什么都不记录  
	错误,     //只记录严重错误  
	警告,     //记录严重错误,普通错误  
	致命,   //记录严重错误,普通错误,警告  
};  
class CLog{

public:
	CLog();
	~CLog();
	//写日志方法
	void Log(string msg,LogLevel level );
protected:
	//初始化
	void GetExeName();
	//获取当前系统时间
	string GetCurrentTime();
	string m_Name;
	string m_Path;
};
#endif
//Log.cpp文件
#include "stdafx.h"
#include "Log.h"
#include <fstream>  
CLog::CLog()
{
	if (m_Name.size()>0) m_Name.clear();
	if (m_Path.size()>0) m_Path.clear();
	this->GetExeName();
	
}
CLog::~CLog()
{
	
}
void CLog::GetExeName()
{
    // 取进程执行文件名称
	char szExeName[MAX_PATH ]={0};  
	//GetModuleFileNameA(NULL, szExeName, MAX_PATH);
	if ( ::GetModuleFileNameA(NULL, szExeName, MAX_PATH) > 0)//获取当前进程已加载模块的文件的完整路径
	{
		char* pBegin = szExeName;
		char* pTemp  = szExeName;
		


		while ( *pTemp != 0 )
		{
			if ( *pTemp == '\\' )
			{
				pBegin = pTemp + 1;


			}
			pTemp++;


		}
		//(strrchr(szExeName, '\\'))[0] = 0; // 删除文件名,只获得路径字串  
		m_Path.insert(0,szExeName);
		m_Name.insert(0,pBegin);
		int a = m_Name.find('.');
		m_Name.erase(a);
		ZeroMemory(szExeName,sizeof(szExeName));
		sprintf_s(szExeName,"%s%s",m_Name.c_str(),".log");
		m_Name.clear();
		m_Name.insert(0,szExeName);
		
	}
}
void CLog::Log(string msg,LogLevel level )
{
	ofstream outfile;  
	outfile.open(m_Name.c_str(),ios::out|ios::app|ios::ate);
  switch(level)
  {
	  case 信息:
		  if (outfile.is_open()) outfile<<this->GetCurrentTime().c_str()<<m_Path.c_str()<<": "<<msg.c_str()<<" -->信息"<<endl;
		  break;
	  case 错误:
		  if (outfile.is_open()) outfile<<this->GetCurrentTime().c_str()<<m_Path.c_str()<<": "<<msg.c_str()<<" -->错误"<<endl;
		  break;
	  case 警告:
		  if (outfile.is_open()) outfile<<this->GetCurrentTime().c_str()<<m_Path.c_str()<<": "<<msg.c_str()<<" -->警告"<<endl;
		  break;
	  case 致命:
		  if (outfile.is_open()) outfile<<this->GetCurrentTime().c_str()<<m_Path.c_str()<<": "<<msg.c_str()<<" -->致命"<<endl;
		  break;
  }
  outfile.close();
}


string CLog::GetCurrentTime()
{
	struct tm t;   //tm结构指针
	time_t now;  //声明time_t类型变量
	time(&now);      //获取系统日期和时间
	localtime_s(&t, &now);   //获取当地日期和时间
	char temp[50] = {0};
	sprintf_s(temp,"[%d-%d-%d %d:%d:%d]" ,t.tm_year + 1900,t.tm_mon + 1,t.tm_mday,t.tm_hour,t.tm_min,t.tm_sec);	
	std::string  pTemp=temp;
	return pTemp;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值