Search code examples
objective-ciosloggingnslog

NSLog vs. Xcode breakpoint logging and creating log files


Would you rather recommend using NSLog or the logging feature provided by Xcode for breakpoints for debugging?

Is there any advantage of using NSLog?

For apps which are running on customer devices: Is there a easy way to log the NSLog or equivalent output to a file or web service?


Solution

  • Personally, I would recommend using both logging (via NSLog) as well as setting breakpoints. Perhaps your question is when you should use one versus the other.

    Advantages of Debugging via Breakpoints / GDB

    • Stops flow of program (use logging if you don't want to stop flow of program)
    • Shows all local variables
    • Can pass objective c messages and make c calls. Flexible way of on the fly answering questions you may have about the current state.

    Breakpoints are nice when you want to get into the code and step by step observe whats going on. Some advantages to stepping through the code include being able to examine any variable you like and being able to execute code via gdb (see Objective-C Debugging tips in Xcode4? for more on gdb tips). Breakpoints are also convenient since you don't have to recompile and add log statements.

    Also see How to set a conditional breakpoint in Xcode based on an object string property?

    Advantages of Logging

    • Does not interrupt flow of program
    • Provides a way of aggregating debugging data
    • Can be viewed on others devices via Organizer
    • If you use TestFlight with the TestFlight SDK, you can capture logs in sessions, which is particularly nice when the app crashes.

    Logs are nice for information you always want to see. For example, an app that downloads resources might want to log each resource that was downloaded (url and whatever other info you may wish). I like to create conditional logs using a macro called DLOG so that I can see more verbose logs just for development but strip these out for release builds.

    DLog (Logging for DEBUG Builds Only)

    #ifdef DEBUG
        #define DLog(...) NSLog(__VA_ARGS__)
    #else
        #define DLog(...) /* */
    #endif
    

    This will only emit NSLog messages for a DEBUG build. You could add similar functionality to facilitate a form of verbose logging for a complicated part of your app. When I'm debugging dragging problems, I find it's often nice to have logs just to watch what's going on (rather than step through everything). However, when I'm done developing the feature or fixing the issue, I definitely am no longer interested in these logs, so I'll typically conditionally show these logs so that if I run into an issue later I can once again view the logs.