C++多线程日志类-创新互联
#ifndef LOGGER_H
#define LOGGER_H
#include#include#include#includeclass Logger
{
public:
enum class LogLevel
{
ERROR,
INFO,
DEBUG
};
typedef struct _stLogInfo
{
std::string info;
LogLevel level;
}stLogInfo;
private:
Logger();
~Logger();
static void createInstance();
std::string getLogLevelString(LogLevel level);
void processEntries();
void setLogFile(std::string file);
std::string getLogFile();
std::string getFileName();
public:
static Logger* getInstance();
Logger(const Logger& obj) = delete ;
Logger& operator=(const Logger& obj) = delete ;
void setLogLevel(LogLevel level);
void log(std::string entry,LogLevel level);
private:
static Logger* m_pInstance;
std::mutex m_mutex;
std::condition_variable m_condVar;
std::queuem_queue;
std::thread m_thread;
bool m_bExit;
LogLevel m_logLevel = LogLevel::ERROR;
std::string m_logFile;
class DestoryPtr
{
public:
~DestoryPtr()
{
if(Logger::m_pInstance)
{
delete Logger::m_pInstance;
Logger::m_pInstance = nullptr;
}
}
};
};
#endif // LOGGER_H
创新互联公司是一家专业提供巴林左旗企业网站建设,专注与网站设计、成都网站建设、H5技术、小程序制作等业务。10年已为巴林左旗众多企业、政府机构等服务。创新互联专业网站建设公司优惠进行中。#include "logger.h"
#include#include#include#includeusing namespace std;
Logger* Logger::m_pInstance = nullptr;
once_flag g_flag;
Logger::Logger()
:m_bExit(false)
{
m_thread = thread(&Logger::processEntries,this);
}
Logger::~Logger()
{
{
unique_locklock(m_mutex);
m_bExit = true;
m_condVar.notify_all();
}
m_thread.detach();
}
void Logger::createInstance()
{
m_pInstance = new Logger;
static DestoryPtr desPtr;
}
std::string Logger::getLogLevelString(Logger::LogLevel level)
{
switch (level)
{
case LogLevel::ERROR:
return "ERROR";
case LogLevel::INFO:
return "INFO";
case LogLevel::DEBUG:
return "DEBUG";
}
return "Invalid log level";
}
Logger *Logger::getInstance()
{
call_once(g_flag,createInstance);
return m_pInstance;
}
void Logger::setLogLevel(LogLevel level)
{
m_logLevel = level;
}
void Logger::processEntries()
{
string file = getFileName();
ofstream logFile(file,ios::app);
if(logFile.fail())
{
//cout<lock(m_mutex);
while(true)
{
if(!m_bExit)
m_condVar.wait(lock);
lock.unlock();
while (true)
{
lock.lock();
if(m_queue.empty())
break;
else
{
file = getFileName();
if(strcmp(file.c_str(),m_logFile.c_str()) != 0)
{
logFile.close();
logFile.open(file,ios::app);
if(logFile.fail())
{
return;
}
setLogFile(file);
}
logFile<<"["<< __TIME__<<"]-->";
logFile<<"["<lock(m_mutex);
if(level >m_logLevel)
return;
stInfo.info = entry;
stInfo.level = level;
m_queue.push(stInfo);
m_condVar.notify_all();
}
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧
网站名称:C++多线程日志类-创新互联
文章网址:http://ybzwz.com/article/dogihe.html