一个简单实用的C++日志类

        最近做c++开发,需要对软件状态做一个日志记录,发现开源的实现很多,但感觉太大了,动不动就几十个Cpp文件。我的东西还要跑在嵌入式设备上呢?不就写个日志吗,“”噼噼啪啪“”,一个下午就搞定! 在此做一个简单记录吧,供自己日后参考! 

  Log.H头文件

#pragma once
#include <fstream>
#include <iostream>
#include<string>
#if defined(_WIN32) || defined(_WIN64)
#include<mutex>
#else
#include <pthread.h>
#include<string.h>
#endif

using namespace std;
enum  LogLevel
{
	LogInfo,
	LogError,
};
class LOG
{

public:

	static void Init();
	static void Finallay();
	static void WriteInfo(LogLevel level, string msg);
	static LogLevel logLevel;
private:
	static ofstream outfile;
#if defined(_WIN32) || defined(_WIN64)
	static std::mutex fileLock;
#else
	static pthread_mutex_t fileLock;
#endif 
};

Log.Cpp

#if defined(_WIN32) || defined(_WIN64)
#include <stdio.h>
#include <direct.h>
#include <stdlib.h>
#else 

#include <time.h>
#include <unistd.h>   
#endif
#include <ctime>
#include"Log.h"

#if defined(_WIN32) || defined(_WIN64)
  std::mutex LOG::fileLock;
#else 
  pthread_mutex_t LOG::fileLock;
#endif



std::ofstream LOG::outfile;
LogLevel  LOG::logLevel;
void LOG::Init()
{
#if defined(_WIN32) || defined(_WIN64)
	char buffer[255];
	_getcwd(buffer, 255);
	string logDir = buffer;
	outfile.open(logDir + "\\log.log", ios::out | ios::in | ios::app);
#else 
	char buf[255];
	getcwd(buf, sizeof(buf));
	printf("currdir:");
	printf(buf);
	string logFilePath = string(buf) + "/log.log";
	outfile.open(logFilePath, ios::out | ios::in | ios::app);
#endif
	logLevel = LogLevel::LogInfo;
}



void LOG::Finallay()
{
	outfile.close();
}
void   LOG::WriteInfo(LogLevel level, string msg)
{
	if (level < logLevel)
		return;

	//long size = ftell(outfile);
	//ofstream fileout("A.txt", ios::trunc); 
	char buffer[200];
#if defined(_WIN32) || defined(_WIN64)
	struct  tm ltm;
	time_t now = time(0);
	localtime_s(&ltm, &now);
	sprintf_s(buffer, "%4d-%.2d-%.2d %.2d:%.2d:%.2d : ", 1900 + ltm.tm_year, 1 + ltm.tm_mon, ltm.tm_mday, ltm.tm_hour, ltm.tm_min, ltm.tm_sec);

#else
	struct tm ltm;
	time_t now = time(0);
	localtime_r(&now, &ltm);
	snprintf(buffer, 200, "%4d-%.2d-%.2d %.2d:%.2d:%.2d : ", 1900 + ltm.tm_year, 1 + ltm.tm_mon, ltm.tm_mday, ltm.tm_hour, ltm.tm_min, ltm.tm_sec);

#endif

	//tm *ltm = localtime_s(&t,&now);
#if defined(_WIN32) || defined(_WIN64)
	fileLock.lock();
	outfile << buffer;
	outfile << msg << endl;
	fileLock.unlock();
#else
	pthread_mutex_lock(&fileLock);
	outfile << buffer;
	outfile << msg << endl;
	pthread_mutex_unlock(&fileLock);
#endif 
}

使用方法:

#include"log.h"

void main()

{

LOG::Init();

LOG::WriteInfo(LogLevel,"msg");

}

猜你喜欢

转载自blog.csdn.net/liaogaobo2008/article/details/82709989