跟踪与调试

/*
    许多C++程序员在跟踪代码时通常的做法是,定义一个简单的Trace类将诊断信息打印到日志文件中。程序员
可以在每个想要跟踪的函数中定义一个Trace对象,在函数的入口和出口Trace类可以分别写一条信息。
    缺点:增加程序开销,必须重新编译程序来打开或关闭跟踪。
    我的博客:
http://blog.csdn.net/windows_nt
*/

class Trace
{
public:
	Trace(const CString &name);
	~Trace();
	void debug(const CString &msg);
	static BOOL traceIsActive;
private:
	CString theFunctionName;
};

//合适的地方做初始化
BOOL Trace::traceIsActive = TRUE;

Trace::Trace(const CString &name) : theFunctionName(name)
{
	if (traceIsActive)
	{
		OutputDebugString(L"Enter function: " + name + L"\n");
	}
}

void Trace::debug(const CString &msg)
{
	if (traceIsActive)
	{
		OutputDebugString(msg);
	}
}

Trace::~Trace()
{
	if (traceIsActive)
	{
		OutputDebugString(L"Exit function: " + theFunctionName + L"\n");
	}
}

//以上的代码存在性能问题,优化版:
class Trace
{
public:
	Trace(const TCHAR* name, ... );
	~Trace();
	void debug(const TCHAR* msg);

	static BOOL traceIsActive;
private:
	CString* theFunctionName;
};

//合适的地方做初始化
BOOL Trace::traceIsActive = TRUE;

inline Trace::Trace(const TCHAR* name, ... ) : theFunctionName(NULL)
{
	va_list args;
	va_start(args, name);

	CString csMsg;
	csMsg.FormatV(name, args);
	va_end(args);  

	if (traceIsActive)
	{
		CString strOutput; 
		strOutput.Format(L"Enter function: %s\n", csMsg );
		OutputDebugString (strOutput);
		theFunctionName = new CString(csMsg);
	}
}

void Trace::debug(const TCHAR* msg)
{
	if (traceIsActive)
	{
		OutputDebugString( *msg + L"\n");
	}
}

inline Trace::~Trace()
{
	if (traceIsActive)
	{
		OutputDebugString(L"Exit function " + *theFunctionName + L"\n");
		delete theFunctionName;
	}
}

//调用方式
{
#ifdef MyDebug
	TCHAR pOutputchar[] = L"OnBnClickedOk()";
	TCHAR pOutputchar2[] = L"OnBnClickedOk2()";
	Trace trace(_T("参数1:%s,参数2:%s"), pOutputchar, pOutputchar2);
#endif
}


你可能感兴趣的:(跟踪与调试)