日志包装器

本文介绍如何在C++中自定义异常类和日志记录功能,通过提供简单实用的Exception类及Debug类实现错误处理与信息记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

虽然现在有许多成熟的日志工具可供选用,但是自己编写一个日志类可以让你用得更加得心应手。对于抛出异常的处理,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;



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值