在我的 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/