Is there a better way than #if DebugMode for logging

I am creating a C ++ library that will be P / Invoked from C #, so I cannot intercept / debug the C ++ side of things. So I decided to add a magazine to see if something went wrong and where it is happening. I add #define DebugMode 1 to determine if I should register or not. First of all, I'm not very good in C ++, but I know enough to get around. So my questions are:

  • Is there a better way than wrapping #if DebugMode #endif around every call to the log? I could just do this inside the logging method and just go back if logging is not turned on, but does this mean that all these logging lines will be in the assembly?

  • How can I emulate what printf does with its "..." operator, allowing me to pass something like Log("Variable x is {0}", x);

  • Are there any tricks like getting the line number or stack trace information that I can use in the log?

Thanks!

+6
c ++ debugging logging
source share
4 answers

One easy way is to simply define a macro that does nothing if you are not in debug mode. This way you do not need to wrap every call in #ifdef .

A simple implementation could be:

 #if DebugMode #define MY_LOG(string, ...) printf(string, __VA_ARGS__) #else #define MY_LOG(string, ...) #endif 

There are other ways and libraries (like boost), but that will help you quickly.

+5
source share

If the condition is a compile-time constant, then your code (after preprocessing) works something like this:

 if (0) do the logging 

Then the compiler will usually be smart enough to cut dead code, including the lines that you passed to it (unless you also used the lines in other code that was not deleted, of course).

Code that acts like printf is pretty simple:

 #include <stdarg.h> void log(char const &fmt, ...) { if (do_logging) { va_list args; va_start(args, fmt); vfprintf(output_file, fmt, args); } } 

In a macro (it’s important that it is in the macro, not the function being called), you can use __FILE__ and __LINE__ for the current line number and the name of the source file for logging. With the above code, you probably want to pass them before the format string.

+2
source share

I recommend using Pantheios and you never have to worry about DEBUG /! DEBUG. The library uses C ++ templates to ensure that performance costs are not paid if registration is not enabled. It is also 100% type safe and extends to custom types.

 bar_t bar; pantheios::log_DEBUG("foo ", bar, " was doing something you should remember"); 

See the page for more information .

+2
source share

How about debugging a C ++ library? In the C ++ library "Project Properties", "Debug", select "C # Client" in the "Command" field and start debugging.

About registration, do you ask about registration in C ++ or C #? The bot has preprocessor constants defined only in the debug configuration, you can use it.

0
source share

All Articles