How to create functions like std::cout?

后端 未结 6 643
盖世英雄少女心
盖世英雄少女心 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 16:53

    You could define an enum like

    enum loglevel_en {
        log_none, log_debug, log_info, log_waring, log_error };
    

    then have a global variable:

    enum loglevel_en my_log_level;
    

    and provide some way to set it (e.g. from program arguments).

    At last, define a macro (in a global header)

    #define MY_LOG(Lev,Thing) do { if (my_log_level >= Lev) \
        std::cout << __FILE__ << ":" << __LINE__ \
                  << " " << Thing << std::endl; } while(0)
    

    and use it like

     MY_LOG(log_info, "x=" << x)
    

    Feel free to improve MY_LOG macro to output more things (date, etc...)

    You could define instead

    #define LOG(Lev) if (my_log_level >= Lev) std::cout 
    

    but that does not play nice with code like

    if (x>34)
      LOG(log_info) << "strange x=" << x;
    else return;
    

    So I strongly suggest something like MY_LOG

提交回复
热议问题