gpt4 book ai didi

c++ - 如何在项目中实现良好的调试/日志记录功能

转载 作者:IT老高 更新时间:2023-10-28 22:36:34 25 4
gpt4 key购买 nike

我正在做一个小项目,总共大约 3-4 人。我希望有一种可靠的方式来调试应用程序,例如通过日志。有没有关于如何构建它的好资源?我从项目经理那里听到很多关于良好的日志记录功能对每个项目都至关重要的信息,但我不知道该怎么做。

最佳答案

我找到了 Dobb 博士的这篇文章,Logging In C++ ,对于这个主题非常有用。

Dobb 博士也有:A Highly Configurable Logging Framework In C++

如果你想要的只是一个简单的线程安全日志类,它总是输出到 stderr 那么你可以使用我写的这个类:

#ifndef _LOGGER_HPP_
#define _LOGGER_HPP_

#include <iostream>
#include <sstream>

/* consider adding boost thread id since we'll want to know whose writting and
* won't want to repeat it for every single call */

/* consider adding policy class to allow users to redirect logging to specific
* files via the command line
*/

enum loglevel_e
{logERROR, logWARNING, logINFO, logDEBUG, logDEBUG1, logDEBUG2, logDEBUG3, logDEBUG4};

class logIt
{
public:
logIt(loglevel_e _loglevel = logERROR) {
_buffer << _loglevel << " :"
<< std::string(
_loglevel > logDEBUG
? (_loglevel - logDEBUG) * 4
: 1
, ' ');
}

template <typename T>
logIt & operator<<(T const & value)
{
_buffer << value;
return *this;
}

~logIt()
{
_buffer << std::endl;
// This is atomic according to the POSIX standard
// http://www.gnu.org/s/libc/manual/html_node/Streams-and-Threads.html
std::cerr << _buffer.str();
}

private:
std::ostringstream _buffer;
};

extern loglevel_e loglevel;

#define log(level) \
if (level > loglevel) ; \
else logIt(level)

#endif

像这样使用它:

// define and turn off for the rest of the test suite
loglevel_e loglevel = logERROR;

void logTest(void) {
loglevel_e loglevel_save = loglevel;

loglevel = logDEBUG4;

log(logINFO) << "foo " << "bar " << "baz";

int count = 3;
log(logDEBUG) << "A loop with " << count << " iterations";
for (int i = 0; i != count; ++i)
{
log(logDEBUG1) << "the counter i = " << i;
log(logDEBUG2) << "the counter i = " << i;
}

loglevel = loglevel_save;
}

关于c++ - 如何在项目中实现良好的调试/日志记录功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6168107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com