什么是生成详细输出的好习惯? [英] What is good practice for generating verbose output?

查看:146
本文介绍了什么是生成详细输出的好习惯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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 );
}

辅助功能 log 被做了模板得到好的调用语法。然后它可以以下列方式使用:

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;
}

您可以通过更改全局 GLOBAL_LEVEL 变量。

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

这篇关于什么是生成详细输出的好习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆