C++ 簡易 Call Stack Logger

// indent level tracker
static unsigned int indent_level;
std::string head(){  return std::string(indent_level++, ' '); };
std::string tail(){ return std::string(--indent_level, ' '); };

// RAII printing tool
struct func_logger
{
    func_logger(const char* name):name_(name)
    {
        std::cout << head() << name_ << std::endl;
    }
    ~func_logger()
    {
        std::cout << tail() << "~" << name_ << std::endl;
    }
    const char* name_;
};

// simplify usage via macro
#ifdef NDEBUG
#define log_func
#else
#define log_func func_logger func_logger_(__FUNCTION__)
#endif
Usage
void eat()
{
    log_func;
    eat_a_lot();
}
void eat_a_lot()
{
    log_func;
}
Output
eat
 eat_a_lot
 ~eat_a_lot
~eat
comments powered by Disqus