c++ - 如何添加易于在需要时打开和关闭而不产生生产开销的日志?

标签 c++

在我的 C# 项目中,我喜欢使用 ConditionalAttribute 并发现它非常有用。我有很多用于日志记录的类,只需重新编译并设置或取消设置相应的条件属性,我就可以打开或关闭日志记录(没有开销)。

// this code likely is not good as HedgerControllerLogger better to be singleton
// please ignore that

public class HedgerControllerLogger
{
    private StreamWriter swLog;

    public HedgerControllerLogger()
    {
        swLog = new StreamWriter("logsGeneral/logHedgerController.txt") { AutoFlush = true };
    }

    [Conditional("LOG_HEDGER_CONTROLLER")]
    public void Log(string message)
    {
        swLog.WriteLine(DateTimePrecise.Instance.CurDateTime().ToString("H:mm:ss:ffffff") + ' ' + message);
    }

}

如何在 C++ 上实现相同的效果?我应该使用类似的东西吗?可能一些现有的日志记录库具有相同的功能,可能是 boost?谢谢!

最佳答案

你可以使用预处理器:

#ifdef ENABLE_LOGGING
  void log(const std::string& message) { /* do logging*/}
#else
  void log(const std::string&){}
#endif

您也可以使用模板做类似的事情,但为什么要把事情搞得过于复杂呢?

关于c++ - 如何添加易于在需要时打开和关闭而不产生生产开销的日志?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16196728/

相关文章:

c++ - 编译 boost 信号2的问题

c++ - 通过继承实现接口(interface)

c++ - 将 MPI 数据类型返回给 MPI Gather

c++ - 是什么导致了这次崩溃?

c++ - QListWidget行互相重叠

c++ - 在 C++ 中用 cin 读取同一行中的多个整数

c++ - 具有 const 和非常量返回引用的重载函数

c++ - 'catkin_make' 期间 ROS hydro opencv2 链接错误

c++ - 如何使用 C++ 以编程方式更新组策略?

c++ - 构造函数中的 Malloc