该类的作用
选择性打印输出到控制台(通过宏定义控制) 将需要的相关日志信息保存到文件中,方便查看程序运行状态和可能发生的错误
代码
// log.hpp
#ifndef __LOG__
#define __LOG__
#include <mutex>
#include <string>
#include <iostream>
#include <sstream>
#include <mutex>
#include <ctime>
#include <cstdio>
#include <cstring>
using namespace std;
//#define __DEBUGE__ //控制台输出控制
class Log{
public:
Log(string logFilePath,string logType){
pfile = fopen(logFilePath.c_str(),"w");
if(pfile == nullptr){
printf("open log file error\n");
return;
}
this->logType = logType;
}
~Log(){
if(pfile){
fclose(pfile);
pfile = nullptr;
}
}
public:
static string getCurrentTime(){
std::time_t now = std::time(nullptr);
char buf[20];
std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
return std::string(buf);
}
string getlogType(){
return this->logType;
}
public:
template<typename T>
Log& operator <<(const T& message){
if(pfile == nullptr){
printf("error:not exist log file\n");
}
logLock.lock();
std::ostringstream msgStream;
msgStream << message;
std::string msgStr = msgStream.str();
fwrite(msgStr.c_str(),1,msgStr.size(),pfile);
#ifdef __DEBUGE__
printf("%s",msgStr.c_str());
#endif
logLock.unlock();
return *this;
}
private:
FILE* pfile;
string logType;
mutex logLock;
};
#endif
使用示例
// main.cpp
#include"log.hpp"
int main(){
Log errorlog("../log/error.log","error");
Log infolog("../log/info.log","info");
errorlog<<"this is a error message,you can find this log in ../log/error.log"<<"\n";
infolog<<"this is a info message,you can find this log in ../log/info.log"<<"\n";
return 0;
}