samedi 19 novembre 2022

Compiling out strings used in print statements in multi-level log - C++

I'm looking for a way to compile print strings out of my binary if a specific macro-based condition is met.

here, _dLvl can be conditionally set equal or lower than the maximum allowed level.


enum DEBUG_LEVELS : int
{
    DEBUG_NONE,
    DEBUG_ERRORS,
    DEBUG_WARN,
    DEBUG_INFO,
    DEBUG_VERBOSE
};

#define MAX_LEVEL  DEBUG_WARN

int _dLvl = DEBUG_ERRORS;

template <typename... Args> void E(const char * _f, Args... args){
    if (_dLvl >= DEBUG_ERRORS){
        printf(_f, args...);
    }
}
template <typename... Args> void W(const char * _f, Args... args){
    if (_dLvl >= DEBUG_WARN){
        printf(_f, args...);
    }
}
template <typename... Args> void I(const char * _f, Args... args){
    if (_dLvl >= DEBUG_INFO){
        printf(_f, args...);
    }
}
template <typename... Args> void V(const char * _f, Args... args){
    if (_dLvl >= DEBUG_VERBOSE){
        printf(_f, args...);
    }
}

int main(){
    E("This will print\n");
    W("This might be printed based on _dLvl, existence of this string is ok.\n");
    I("This wont print ever, the existence of this string is memory waste\n");
    V("Same as I\n");
}

What adds to the challenge that I've multiple instances of a logger class, where each instance would have a different MAX level, see this question for a more clear example of multi-instances.

Here's a solution for my situation (but an ugly and unmanageable onewherein it requires a special macro per instance to be used differently within the source code):

#if (WIFI_LOG_MAX_LEVEL >= 1)
#define w_log_E(f_, ...) logger.E((f_), ##__VA_ARGS__)
#else
#define w_log_E(f_, ...)
#endif

#if (WIFI_LOG_MAX_LEVEL >= 2)
#define w_log_W(f_, ...) logger.W((f_), ##__VA_ARGS__)
#else
#define w_log_W(f_, ...)
#endif

#if (WIFI_LOG_MAX_LEVEL >= 3)
#define w_log_I(f_, ...) logger.I((f_), ##__VA_ARGS__)
#else
#define w_log_I(f_, ...)
#endif

#if (WIFI_LOG_MAX_LEVEL >= 4)
#define w_log_V(f_, ...) logger.V((f_), ##__VA_ARGS__)
#else
#define w_log_V(f_, ...)
#endif

Is there any trick to solve it?

Aucun commentaire:

Enregistrer un commentaire