2

Does anyone know how to dynamically get all the variables values passed into a function for the sake of logging ?

I'm looking for a simple way (like using a compiler macro) to be able to log the function, and the variable values passed into it (which will then be written to a log file so we can easily find inputs that cause functions to crash)

I've been trying

#define NFDebug( s, ... ) NSLog( @"DEBUG: %s: %@", __PRETTY_FUNCTION__, \
[NSString stringWithFormat:(@"%@"), ##__VA_ARGS__] )

,which gives everything, BUT the variables values

1 Answer 1

1

I use something like this:

#ifdef YOUR_DEBUG_ENABLER_SYMBOL_ONLY_SET_IN_DEBUG_BUILDS
#define DEBUG_ONLY(_code_) _code_
#else
#define DEBUG_ONLY(_code_)
#endif

#define DebugLog(_str, ...) DEBUG_ONLY(NSLog(@"%s: " _str, __func__, ## __VA_ARGS__))

Note that there is no comma before the _str in the NSLog - this means the string you use in your calling code is appended (by the compiler) to the "%s: " string to become a composite format string for the NSLog. Whatever parameters you want to print can be included in your passed in format string. The %s applies to the _ _ func _ _ and your _str applies to the rest of the passed in variables:

float f;
int i;
NSString* s;
// Initialise f, i, and s to something
...
// Log the values only when in debug mode, with function name auto-prepended
DebugLog(@"float is: %f - int is: %d - string is: %@", f, i, s);

This has the advantage that you can log whatever text and variables you want, conditionally on debug, and with the function name automatically prepended onto the output.

Sign up to request clarification or add additional context in comments.

1 Comment

I left it out for simplicity above, but actually I have different log-levels (DebugLog0, DbugLog1, etc.) so you can set the log-level you want and get more/less logging as desired. This can be done in two ways: log-level set at compile-time; or alternatively log-level set at run-time. You can easily add/expand on this. It also makes sense to have DebugAssert, DebugWarn, ReleaseLog, and ReleaseError macros.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.