#include <iostream>
#include <Mutex>
#include <ctime>
std::mutex mt;
//时间间隔类
class Duration
{
public:
explicit Duration() : m_start(clock()){}
double duration()
{
m_finish = clock();
double d = (double)(m_finish - m_start) / CLOCKS_PER_SEC;
return d;
}
private:
clock_t m_start, m_finish;
};
//日志记录器
class DLogger
{
public:
enum Log_Grade
{
Debug = 0,
Info,
Warn,
Error,
Fatal
};
public:
explicit DLogger(const std::string& fileName = "unknow")
{
if(fileName == "unknow")
{
char buf[64];
time_t now = time(0);
tm* ltm = localtime(&now);
sprintf(buf, "%d-%d-%d.log", ltm->tm_year + 1900, ltm->tm_mon + 1, ltm->tm_mday);
m_fileName = buf;
}
else
{
m_fileName = fileName;
}
}
void log(const char* msg, Log_Grade grade = Info);
private:
std::string m_fileName;
};
void DLogger::log(const char* msg, Log_Grade grade)
{
mt.lock();
FILE* fp = ::fopen(m_fileName.data(), "a+");
char buf[1024];
::sprintf(buf, "%s, %s, %s, %d, %s, %d\n", __DATE__, __TIME__, __FILE__, __LINE__, msg, grade);
::fwrite(buf, sizeof(char),strlen(buf), fp);
::fclose(fp);
mt.unlock();
}
//运行测试类
class Worker
{
public:
explicit Worker(DLogger *logger = nullptr) : m_pLogger(logger){}
~Worker()
{
if(m_pLogger)
{
delete m_pLogger;
m_pLogger = nullptr;
}
}
void run()
{
if(nullptr == m_pLogger)
{
std::cout << "nullptr == m_pLogger" << std::endl;
return;
}
Duration d;
for(int i = 0; i < 1000; ++i)
{
m_pLogger->log("work message", DLogger::Warn);
}
std::cout << "duration: " << d.duration() << " seconds" << std::endl;
}
private:
DLogger *m_pLogger;
};
int main()
{
Worker w(new DLogger);
w.run();
return 0;
}
转载于:https://www.cnblogs.com/chengjundu/p/11276689.html