生成详细输出的良好做法是什么?

发布于 2024-08-01 14:40:15 字数 383 浏览 5 评论 0原文

生成详细输出的良好做法是什么? 目前,我有一个函数

bool verbose;
int setVerbose(bool v)
{
    errormsg = "";
    verbose = v;
    if (verbose == v)
        return 0;
    else
        return -1;
}

,每当我想生成输出时,我都会执行类似的操作

if (debug)
     std::cout << "deleting interp" << std::endl;

,但是我认为这不是很优雅。 所以我想知道实现这种详细程度切换的好方法是什么?

what is good practice for generating verbose output? currently, i have a function

bool verbose;
int setVerbose(bool v)
{
    errormsg = "";
    verbose = v;
    if (verbose == v)
        return 0;
    else
        return -1;
}

and whenever i want to generate output, i do something like

if (debug)
     std::cout << "deleting interp" << std::endl;

however, i don't think that's very elegant. so i wonder what would be a good way to implement this verbosity switch?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

一城柳絮吹成雪 2024-08-08 14:40:16

1. 如果您使用 g++,您可以使用 -D 标志,这允许编译器定义您选择的宏。

定义

例如:

#ifdef DEBUG_FLAG
 printf("My error message");
#endif

2. 我同意这也不优雅,所以为了让它更好一点:

void verbose(const char * fmt, ... )
{
va_list args;  /* Used as a pointer to the next variable argument. */
va_start( args, fmt );  /* Initialize the pointer to arguments. */

#ifdef DEBUG_FLAG
printf(fmt, &args);  
#endif
/*This isn't tested, the point is to be able to pass args to 
printf*/
}

您可以像 printf 一样使用:

verbose("Error number %d\n",errorno);

3. 第三种解决方案更简单,更类似于 C++ 和 Unix 的方法是将一个参数传递给您的程序,该程序将被使用(如前面的宏)来初始化特定变量(可能是全局 const)。

例子 :
$ ./myprogram -v

if(optarg('v')) static const verbose = 1;

1. If you are using g++ you could use the -D flag, this allows the compilator to define a macro of your choice.

Defining the

For instance :

#ifdef DEBUG_FLAG
 printf("My error message");
#endif

2. I agree this isn't elegant either, so to make it a bit nicer :

void verbose(const char * fmt, ... )
{
va_list args;  /* Used as a pointer to the next variable argument. */
va_start( args, fmt );  /* Initialize the pointer to arguments. */

#ifdef DEBUG_FLAG
printf(fmt, &args);  
#endif
/*This isn't tested, the point is to be able to pass args to 
printf*/
}

That you could use like printf :

verbose("Error number %d\n",errorno);

3. A third solution easier, and more C++ and Unix like is to pass an argument to your program that is going to be used - as the macro earlier - to initialize a particular variable (that could be a global const).

Example :
$ ./myprogram -v

if(optarg('v')) static const verbose = 1;
睡美人的小仙女 2024-08-08 14:40:16
int threshold = 3;
class mystreambuf: public std::streambuf
{
};
mystreambuf nostreambuf;
std::ostream nocout(&nostreambuf);
#define log(x) ((x >= threshold)? std::cout : nocout)

int main()
{
    log(1) << "No hello?" << std::endl;     // Not printed on console, too low log level.
    log(5) << "Hello world!" << std::endl;  // Will print.
    return 0;
}
int threshold = 3;
class mystreambuf: public std::streambuf
{
};
mystreambuf nostreambuf;
std::ostream nocout(&nostreambuf);
#define log(x) ((x >= threshold)? std::cout : nocout)

int main()
{
    log(1) << "No hello?" << std::endl;     // Not printed on console, too low log level.
    log(5) << "Hello world!" << std::endl;  // Will print.
    return 0;
}
好多鱼好多余 2024-08-08 14:40:16

您可以将您的功能包装在支持 << 的类中 运算符允许您执行类似的操作

class Trace {
   public:
      enum { Enable, Disable } state;
   // ...
   operator<<(...)
};

然后您可以执行类似的操作

trace << Trace::Enable;
trace << "deleting interp"

You can wrap your functionality in a class that supports the << operator which allows you to do something like

class Trace {
   public:
      enum { Enable, Disable } state;
   // ...
   operator<<(...)
};

Then you can do something like

trace << Trace::Enable;
trace << "deleting interp"
情释 2024-08-08 14:40:16

您可以使用 log4cpp

You could use log4cpp

风向决定发型 2024-08-08 14:40:16

最简单的方法是创建小类,如下所示(这里是 Unicode 版本,但您可以轻松地将其更改为单字节版本):

#include <sstream>
#include <boost/format.hpp>
#include <iostream>
using namespace std;

enum log_level_t {
    LOG_NOTHING,
    LOG_CRITICAL,
    LOG_ERROR,
    LOG_WARNING,
    LOG_INFO,
    LOG_DEBUG
};

namespace log_impl {
class formatted_log_t {
public:
    formatted_log_t( log_level_t level, const wchar_t* msg ) : fmt(msg), level(level) {}
    ~formatted_log_t() {
        // GLOBAL_LEVEL is a global variable and could be changed at runtime
        // Any customization could be here
        if ( level <= GLOBAL_LEVEL ) wcout << level << L" " << fmt << endl;
    }        
    template <typename T> 
    formatted_log_t& operator %(T value) {
        fmt % value;
        return *this;
    }    
protected:
    log_level_t     level;
    boost::wformat      fmt;
};
}//namespace log_impl
// Helper function. Class formatted_log_t will not be used directly.
template <log_level_t level>
log_impl::formatted_log_t log(const wchar_t* msg) {
    return log_impl::formatted_log_t( level, msg );
}

帮助函数 log 被制作为模板以获得良好的调用语法。 然后可以按以下方式使用它:

int main ()
{
    // Log level is clearly separated from the log message
    log<LOG_DEBUG>(L"TEST %3% %2% %1%") % 5 % 10 % L"privet";
    return 0;
}

您可以通过更改全局 GLOBAL_LEVEL 变量在运行时更改详细级别。

The simplest way is to create small class as follows(here is Unicode version, but you can easily change it to single-byte version):

#include <sstream>
#include <boost/format.hpp>
#include <iostream>
using namespace std;

enum log_level_t {
    LOG_NOTHING,
    LOG_CRITICAL,
    LOG_ERROR,
    LOG_WARNING,
    LOG_INFO,
    LOG_DEBUG
};

namespace log_impl {
class formatted_log_t {
public:
    formatted_log_t( log_level_t level, const wchar_t* msg ) : fmt(msg), level(level) {}
    ~formatted_log_t() {
        // GLOBAL_LEVEL is a global variable and could be changed at runtime
        // Any customization could be here
        if ( level <= GLOBAL_LEVEL ) wcout << level << L" " << fmt << endl;
    }        
    template <typename T> 
    formatted_log_t& operator %(T value) {
        fmt % value;
        return *this;
    }    
protected:
    log_level_t     level;
    boost::wformat      fmt;
};
}//namespace log_impl
// Helper function. Class formatted_log_t will not be used directly.
template <log_level_t level>
log_impl::formatted_log_t log(const wchar_t* msg) {
    return log_impl::formatted_log_t( level, msg );
}

Helper function log was made template to get nice call syntax. Then it could be used in the following way:

int main ()
{
    // Log level is clearly separated from the log message
    log<LOG_DEBUG>(L"TEST %3% %2% %1%") % 5 % 10 % L"privet";
    return 0;
}

You could change verbosity level at runtime by changing global GLOBAL_LEVEL variable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文