现在的位置: 首页 > 综合 > 正文

日志包装器

2018年03月31日 ⁄ 综合 ⁄ 共 1465字 ⁄ 字号 评论关闭

虽然现在有许多成熟的日志工具可供选用,但是自己编写一个日志类可以让你用得更加得心应手。对于抛出异常的处理,C++语言本身并没有做什么东西,可怜的STL也只有一个很简单的异常类,所以下面先给出一个最简单的Exception类。

Exception.h

#ifndef _EXCEPTION_H_
#define _EXCEPTION_H_

#include <string>

class Exception
{
	std::string msg;

public:

	Exception(const char *msg)
	{
		this->msg = msg;
	}

	const char *getMessage()
	{
		return msg.c_str();
	}
};

#endif

在接下来的Debug类中需要用到该Exception类。

Debug.h

#ifndef _DEBUG_H_
#define _DEBUG_H_

#include <stdio.h>
#include <string>

#include <iostream>
#include <sstream>
#include <fstream>


#include <Exception.h>

class Debug
{
	static bool enabled;

public:

	static void on()
	{
		enabled = true;
	}

	static void off()
	{
		enabled = false;
	}

	static bool isOn()
	{
		return enabled;
	}

	static void message(const char *s)
	{
		if (enabled == true)
			printf("[message] %s\n", s);
	}

	static void message(std::string &s)
	{
		message(s.c_str());
	}



	static void message(std::ostringstream &s)
	{
		message(s.str().c_str());
	}


	static void message(const char *s, const char *fname)
	{
		if (enabled == true) {
			std::fstream fout(fname, std::ios::out|std::ios::app);
			if (fout.fail())
				return;
			fout << "[message] " << s << std::endl;
			fout.close();
		}
	}

	static void warning(const char *s)
	{
		printf("[warning] %s\n", s);
	}

	static void warning(std::string &s)
	{
		warning(s.c_str());
	}


	static void warning(std::ostringstream &s)
	{
		warning(s.str().c_str());
	}


	static void warning(Exception &e)
	{
		warning(e.getMessage());
	}



	static void warning(const char *s, const char *fname)
	{
		std::fstream fout(fname, std::ios::out|std::ios::app);
		if (fout.fail())
			return;
		fout << "[warning] " << s << std::endl;
		fout.close();
	}

};

#endif

剩下的实现就剩下给静态变量赋初始值了。

Debug.cpp

#include <Debug.h>



bool Debug::enabled = false;

【上篇】
【下篇】

抱歉!评论已关闭.