我想为我们的大型C++代码库开发缩进跟踪,这对于开发人员找到问题特别有帮助.我想要缩进跟踪功能.例如,请考虑以下代码: -
void FunctionA()
{
TR_ENTER("Function A");
TR_PRINT("Dignostic message Function A");
FunctionB(); // Call function B
}
void FunctionB()
{
TR_ENTER("Function B");
TR_PRINT("Dignostic message Function B");
FunctionC(); // Call function B
}
void FunctionC()
{
TR_ENTER("Function C");
TR_PRINT("Dignostic message Function C");
}
Run Code Online (Sandbox Code Playgroud)
如您所见,上面的调用彼此嵌套.我想生成跟踪日志,如下所示:
Function A - Start
Dignostic message Function A
Function B - Start
Dignostic message Function B
Function C - Start
Dignostic message Function C
Function C - End
Function B - End
Function A - End
Run Code Online (Sandbox Code Playgroud)
TR_ENTER和TR_PRINT是我用作示例的一些宏.要说函数启动我使用TR_ENTER并打印一些有关消息的消息,我使用了TR_PRINT.
正如您所看到的,嵌套函数调用的跟踪在彼此之间缩进.我是否知道有什么可用的东西,以便我可以阻止自己重新发明轮子.
谢谢,Omky
您需要跟踪呼叫深度:
class trace_entry;
class trace_log {
public:
trace_log() : depth_(0) { }
private:
// noncopyable so we don't accidentally copy it
trace_log(trace_log&);
void operator=(trace_log);
friend trace_entry;
int depth_;
};
class trace_entry {
public:
trace_entry(trace_log& log, const std::string& frame)
: log_(log), frame_(frame) {
std::cout << std::string(4 * log.depth_, ' ')
<< "ENTER " << frame_ << std::endl;
++log_.depth_;
}
~trace_entry() {
--log_.depth_;
std::cout << std::string(4 * log_.depth_, ' ')
<< "EXIT " << frame_ << std::endl;
}
private:
// noncopyable so we don't accidentally copy it
trace_entry(trace_entry&);
void operator=(trace_entry);
trace_log& log_;
std::string frame_;
};
Run Code Online (Sandbox Code Playgroud)
用法示例:
void a(trace_log& log) {
trace_entry e(log, "a");
}
void b(trace_log& log) {
trace_entry e(log, "b");
return a(log);
}
int main() {
trace_log log;
trace_entry e(log, "main");
b(log);
}
Run Code Online (Sandbox Code Playgroud)
输出:
ENTER main
ENTER b
ENTER a
EXIT a
EXIT b
EXIT main
Run Code Online (Sandbox Code Playgroud)
这很容易扩展,以支持其他形式的日志记录,允许其他日志消息,以及您想要做的任何其他事情.(trace_log实际执行日志记录会好得多,但出于展示目的,这是演示您要执行的操作的最简单方法.)