目的:输出自己想要打印的信息,经常会使用到,写了好几次了,易于自己后面直接调用,代码量虽然少,也懒得写(c++实现)
outputlog.h
#pragma once
#include <mutex>
#include <fstream>
#include <string>
#include <time.h>
using namespace std;
enum ENUMLOG_TYEP
{
Type_Info = 0,
Type_Warn,
Type_Error,
Type_Unkown
};
class OutputLog
{
public:
static OutputLog *getInstance();
void printOutLog(ENUMLOG_TYEP type, string data);
private:
OutputLog();
~OutputLog();
class CC //垃圾回收机制
{
public:
~CC()
{
if (m_pInstance != NULL)
{
delete m_pInstance;
m_pInstance = nullptr;
}
}
};
static OutputLog* m_pInstance;
static mutex m_mutex;
time_t nowtime;
static CC cc;
};
outputlog.cpp
#include "OutputLog.h"
OutputLog* OutputLog::m_pInstance = nullptr;
mutex OutputLog::m_mutex;
OutputLog::CC OutputLog::cc;
OutputLog::OutputLog()
{
}
OutputLog::~OutputLog()
{
if (m_pInstance)
{
delete m_pInstance;
m_pInstance = nullptr;
}
}
OutputLog *OutputLog::getInstance()
{
if (m_pInstance)
return m_pInstance;
else
{
m_mutex.lock();
m_pInstance = new OutputLog;
m_mutex.unlock();
return m_pInstance;
}
}
void OutputLog::printOutLog(ENUMLOG_TYEP type, string data)
{
m_mutex.lock();
fstream m_stream;
string info = "";
switch (type)
{
case Type_Info:
info = " Info:"; break;
case Type_Error:
info = " Error:"; break;
case Type_Warn:
info = " Warn:"; break;
default:
info = " Unkown:"; break;
}
struct tm ss;
time(&nowtime);
localtime_s(&ss, &nowtime);
int year = ss.tm_year + 1900;
int month = ss.tm_mon + 1;
int day = ss.tm_mday;
string date = to_string(year) + "-" + to_string(month) + "-" + to_string(day);
string outp = "./outputLog" + date + ".txt";
m_stream.open(outp, ios::out | ios::app);
int hour = ss.tm_hour;
int mint = ss.tm_min;
int sec = ss.tm_sec;
string datetime = date + " " + to_string(hour) + ":" + to_string(mint) + ":" + to_string(sec);
string alldata = datetime + info + data + "\n";
m_stream.write(alldata.c_str(), alldata.size());
m_stream.close();
m_mutex.unlock();
}