How to create functions like std::cout?

后端 未结 6 603
盖世英雄少女心
盖世英雄少女心 2021-01-03 16:40

I\'m creating my own logging utility for my project, I want to create a function like iostream\'s std::cout, to log to a file and print to the console as well.

Here\

6条回答
  •  囚心锁ツ
    2021-01-03 17:09

    I will not enter coding details here, but I will provide you some quick guidelines :

    1. Create a singleton object pool (for loggers is ok to create a singleton) or a namespace or a that returns a certain log class according to the enum :

      Logger& SingletonLoggersManager::GetLoggerForLevel(eLogLevel);

    2. Override the "<<" operator for your class in order to allow outputting accoridng to your needs in your Logger class

    https://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx

    1. Define a macro in order to be able to make a quick call inside your code :

      #define LOG(x) SingletonLogger::GetLoggerForLevel(eLogLoevel);

    Now when you use inside your code

     Log(debug) << "test" 
    

    It will expand to :

     (SingletonLogger::GetLoogerForLevel(debug)) << "test";
    

提交回复
热议问题