c++通过宏控制Log日志的显示与否
当使用log打印日志消息时,有的日志不想输出,所以希望通过参数动态配置显示与否。
采用宏定义和static变量的方式控制日志的显示与否。
代码
- LogController.h
#include <logger.h>
namespace cs {
namespace logger {
class LogController {
private:
static bool isShowLog;
public:
static void setIsShowLog(bool isShow);
static bool getIsShowLog();
};
}
}
#define IS_SHOW_LOG (cs::logger::LogController::getIsShowLog() == true)
#define PRE_LOG(X) LOG(X)
#define LOG_IF(X) if (IS_SHOW_LOG) PRE_LOG(X)
- LogController.cpp
#include "LogController.h"
bool cs::logger::LogController::isShowLog = true;
void cs::logger::LogController::setIsShowLog(bool isShow) {
cs::logger::LogController::isShowLog = isShow;
}
bool cs::logger::LogController::getIsShowLog() {
return cs::logger::LogController::isShowLog;
}
使用
LOG(INFO) << "hello world";
// 替换为
LOG_IF(INFO) << "hello world";
本文介绍了一种使用C++宏和静态变量控制日志显示的方法。通过LogController类的setIsShowLog和getIsShowLog函数,可以动态设置是否显示日志。LOG_IF宏用于在满足日志显示条件时打印日志,从而实现日志输出的控制。

1346

被折叠的 条评论
为什么被折叠?



