简单的日志输出文件类

目的:输出自己想要打印的信息,经常会使用到,写了好几次了,易于自己后面直接调用,代码量虽然少,也懒得写(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();
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值