Is it true that one should not use NSLog() on production code? - iphone

I was told this a few times in this very site, but I wanted to make sure this is really the case.
I was expecting to be able to sprinkle NSLog function calls throughout my code, and that Xcode/gcc would automatically strip those calls out when building my Release/Distribution builds.
Should I avoid using this? If so, what alternatives are most common between experienced Objective-C programmers?

Preprocessor macros are indeed great for debugging. There's nothing wrong with NSLog(), but it's simple to define your own logging function with better functionality. Here's the one I use, it includes the file name and line number to make it easier to track down log statements.
#define DEBUG_MODE
#ifdef DEBUG_MODE
#define DebugLog( s, ... ) NSLog( #"<%p %#:(%d)> %#", self, [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] )
#else
#define DebugLog( s, ... )
#endif
I found it easier to put this entire statement in the prefix header rather than its own file. You could, if you wanted, build a more complicated logging system by having DebugLog interact with normal Objective-C objects. For instance, you could have a logging class that writes to its own log file (or database), and includes a 'priority' argument you could set at runtime, so debug messages are not shown in your release version, but error messages are (if you did this you could make DebugLog(), WarningLog(), and so on).
Oh, and keep in mind #define DEBUG_MODE can be re-used in different places in your application. For example, in my application I use it to disable license key checks and only allow the application to run if it's before a certain date. This lets me distribute a time limited, fully functional beta copy with minimal effort on my part.

Put this 3 lines at the end of -prefix.pch file:
#ifndef DEBUG
#define NSLog(...) /* suppress NSLog when in release mode */
#endif
You don't need to define anything into your project, because DEBUG is defined in your build setting by default when you create your project.

NSLog calls can be left in production code, but should only be there for truly exceptional cases, or information that it is desired that will be logged to the system log.
Applications which litter the system log are annoying, and come across as unprofessional.

I can't comment on Marc Charbonneau's answer, so I'll post this as an answer.
Further to adding the macro to your pre-compiled header, you can use the Target build configurations to control the defining (or lack of defining) the DEBUG_MODE.
If you select "Debug" active configuration, DEBUG_MODE will be defined, and the macro expands to the full NSLog definition.
Selecting the "Release" active configuration will not define DEBUG_MODE and your NSLogging is omitted from the release build.
Steps:
Target > Get Info
Build tab
Search for "PreProcessor Macros" (or GCC_PREPROCESSOR_DEFINITIONS)
Select Configuration: Debug
Edit Definition at this Level
Add DEBUG_MODE=1
Select Configuration: Release
confirm DEBUG_MODE is not set in GCC_PREPROCESSOR_DEFINITIONS
if you omit the '=' character in the definition, you will get an error from the preprocessor
Also, paste this comment (shown below) above the macro definition to remind you where the DEBUG_MACRO define comes from ;)
// Target > Get Info > Build > GCC_PREPROCESSOR_DEFINITIONS
// Configuration = Release: <empty>
// = Debug: DEBUG_MODE=1

EDIT: The method posted by Marc Charbonneau, and brought to my attention by sho, is far better than this one.
I have deleted the portion of my answer which suggested using an empty function to disable logging when debug mode is disabled. The portion that deals with setting an automatic preprocessor macro is still relevant, so it remains. I have also edited the name of the preprocessor macro so that it fits better with Marc Charbonneau's answer.
To achieve the automatic (and expected) behaviour in Xcode:
In the project settings, go to the "Build" tab, and select the "Debug" configuration. Find the "Preprocessor Macros" section, and add a macro named DEBUG_MODE.
...
EDIT: See Marc Charbonneau's answer for the proper way to enable and disable logging with the DEBUG_MODE macro.

I agree with Matthew. There's nothing wrong with NSLog in production code. In fact, it can be useful to the user. That said, if the only reason you're using NSLog is to help debug, then, yes, that should be removed before you release.
Furthermore, since you've tagged this as an iPhone question, NSLog takes resources, which is something the iPhone has precious little of. If you're NSLogging anything on the iPhone, that takes away processor time from your app. Use it wisely.

The simple truth is that NSLog is just plain slow.
But why? To answer that question, let's find out what NSLog does, and then how it does it.
What does NSLog do exactly?
NSLog does 2 things:
It writes log messages to the Apple System Logging (asl) facility. This allows log messages to show up in Console.app.
It also checks to see if the application's stderr stream is going to a terminal (such as when the application is being run via Xcode). If so it writes the log message to stderr (so that it shows up in the Xcode console).
Writing to STDERR doesn't sound difficult. That can be accomplished with fprintf and the stderr file descriptor reference. But what about asl?
The best documentation I've found about ASL is a 10 part blog post from Peter Hosey: link
Without going into too much detail, the highlight (as it concerns performance) is this:
To send a log message to the ASL facility, you basically open a client connection to the ASL daemon and send the message. BUT - each thread must use a separate client connection. So, to be thread safe, every time NSLog is called it opens a new asl client connection, sends the message, and then closes the connection.
Resources could be found here & here.

As noted in other answers you can use a #define to alter whether NSLog is used or not at compile time.
However a more flexible way is to use a logging library like Cocoa Lumberjack thatallows you to change whether something is logged at runtime as well.
In your code replace NSLog by DDLogVerbose or DDLogError etc, add a #import for the macro definitions etc and setup the loggers, often in the applicationDidFinishLaunching method.
To have the same effect as NSLog the configuration code is
[DDLog addLogger:[DDASLLogger sharedInstance]];
[DDLog addLogger:[DDTTYLogger sharedInstance]];

From a security point of view, it depends on what is being logged. If NSLog (or other loggers) is writing sensitive information, then you should remove the logger in production code.
From an auditing point of view, the auditor does not want to look at each use of NSLog to ensure its not logging sensitive information. He/she will simply tell you to remove the logger.
I work with both groups. We audit code, write the coding guides, etc. Our guide requires that logging is disabled in production code. So the internal teams know not to try it ;)
We will also reject an external app that logs in production because we don't want to accept the risk associated with accidentally leaking sensitive information. We don't care what the developer tells us. Its simply not worth our time to investigate.
And remember, we define 'sensitive', and not the developer ;)
I also perceive an app which performs lots of logging as an app ready to implode. There's a reason so much logging is performed/needed, and its usually not stability. Its right up there with 'watchdog' threads that restart hung services.
If you have never been through a Security Architecture (SecArch) review, these are the sorts of things we look at.

You shouldn't be needlessly verbose with printf or NSLog in release code. Try only doing a printf or NSLog if the app has something bad happen to it, I.E. an unrecoverable error.

Keep in mind that NSLogs can slow down the UI / main thread. It is best to remove them from release builds unless absolutely necessary.

I would highly recommend using TestFlight for logging (free). Their method will override NSLog (using a macro) and allow you to turn on/off logging to their server, Apple System log and STDERR log, for all your existing calls to NSLog. The nice thing about this is you can still review your log messages for apps deployed to testers and apps deployed in the App Store, without the logs appearing on the user's system log. The best of both worlds.

Related

Will NSLog effect app's speed? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Do I need to disable NSLog before release Application?
In my iPhone app there are more than 20 classes.Every where I am printing so many values using NSLog.When I run my app on simulator it is bit low because of some NSLogs(specially printing NSData etc)
Will it be slow if I finished the app and run it on device after making the ipa file ?
Or should I comment all the NSLogs from classes ?
yes it does. and if u wanna check it by urself, do profiling with allocations, and see what is taking much of your memory. It will show NSLogs also.
instead of NSLog use DLog everywhere. When testing and debugging, you'll get debug messages. When you're ready to release a beta or final release, all those DLog lines automatically become empty and nothing gets emitted. This way there's no manual setting of variables or commenting of NSLogs required. Picking your build target takes care of it.
NSLog will affect speed as it blocks and causes IO. It runs synchronously in the current thread.
better is something async! -- like cocoalumberjack's DDLog which is a drop in replacement that doesnt block. [still can cause IO, see next info about levels]
ALSO DDLog knows about log levels. E.G. info, Warning & Error:
in release mode you set it to error by default (but it can be changed via a UserDefault value!)
warnings and infos are not logged then which makes it cause only VERY little overhead
DDLog is similar to log4j but for objC!

iPhone RestKit how to enable RKLogDebug?

I'm trying to debug RestKit object mapping and noticed that there are calls to RKLogDebug throughout the code, but it appears that that macro is undefined somewhere. How can I enable it?
You want to add something like this:
RKLogConfigureByName("RestKit", RKLogLevelWarning);
RKLogConfigureByName("RestKit/ObjectMapping", RKLogLevelTrace);
RKLogConfigureByName("RestKit/Network", RKLogLevelTrace);
to your code. See RKLog.h for the various levels. It is pretty trick.
N.B. this supports a wildcard at the end so, e.g.,
RKLogConfigureByName("*", RKLogLevelTrace); // set all logs to trace,
RKLogConfigureByName("RestKit*", RKLogLevelWarning); // set all RestKit logs to warning (leaving the app-specific log untouched).
– Thanks Kevin!
For Swift user use this syntex:
RKlcl_configure_by_name("RestKit/Network", RKlcl_vTrace.rawValue)
RKlcl_configure_by_na`enter code here`me("RestKit/ObjectMapping", RKlcl_vOff.rawValue)
– Thanks Darshit!
As described in first answer you can configure your app to specific component by calling RKLogConfigureByName.
You can also configure RestKit for specific component using Environment Variables in Xcode scheme. This is useful especially when you have your app building continuously for different environments.
Here's detailed explanation of RestKit logging http://restkit-tutorials.com/logging-in-restkit-debug-tips/

Handling errors/exceptions & logging them in iPhone applications

I wanted to know do we need to log the exceptions/errors in a common file in file system when an iPhone application runs for debugging purpose later point in time? Or this is handled by IOS automatically through device logs?
I now using NSLog statements we can print on consol but is there something similar to log4j in Java where you put all debugging statements including errors/exceptions in a single file which you can analyze later point in time.
What is the best way to handle such scenarios.
Some excellent info is found in this previous post on SO:
Logging to a file on the iPhone
Another good tip for logging in general is using the DLog macro:
http://iphoneincubator.com/blog/debugging/the-evolution-of-a-replacement-for-nslog

SDL.NET (VB/C#): What should the startup object and application type be?

I eventually couldn't get any further with my program due to the various shortcomings of VB.NET (bad audio support, no reading events in the middle of execution, very weak keyboard input, etc). So I tried SDL.NET 6.1.
Despite its terrible documentation, I was able to fix my code to use it and I love it!
But there's a problem. I don't know how to set up my application settings for it. The Startup Object definitely should be a class (the examples always are in classes, never modules), but a startup class specifically has to be a form! This is bad because SDL makes its own window via SetVideoMode; you don't need a form. So when the form constructor New() finishes, a useless form is created and you have two windows.
I tried placing a call to the game engine loop within New() so that the game starts up without New() ever finishing. The game runs normally, and this solves the "second window" problem... but it can't be closed! X button does nothing, calls to Events.QuitApplication or Me.Close are blatantly ignored, etc.
I'm stumped. It seems I need to set a non-form class as the startup object, but it won't let me.
Oh, by the way, it seems that there are two things called "SDL NET". To clarify, I'm using this one, which exists in the SdlDotNet namespace.
Oh, I forgot to mention, I also noticed that a lot of the examples have a line that says "[STAThread]". Is this is important?
EDIT:
I've already received and accepted an answer for my question, but I want to tell other people what the problem is with exiting/closing the app, even though that wasn't my question:
While SDL.NET allows you to receive input and run other events without having to stop running logic, the application still cannot quit while logic is being run. So I find the best way to tell your SDL.NET application to Quit in the middle of running logic is to use the following TWO lines:
SdlDotNet.Core.Events.QuitApplication
End
Place these in the handler for the SdlDotNet.Core.Events.Quit event, as well as anywhere else you want your program to quit.
The Startup Object definitely should be a class (the examples always are in classes, never modules)
Here's your mistake. There's no real difference between a class and a VB module from CLR perspective. So just make it a module with Main and go on. There is no need for a class. I suspect you're looking at C# examples, which use classes - but that's because there is no such thing as a module in C#.
[STAThread] probably won't make any difference for SDL. It is important for UI applications (both WinForms and WPF require it), but I don't think that SDL does any COM calls, so it shouldn't care whether your thread is STA or not. It's just something that Visual Studio puts on Main in new projects by default.

How to add NSDebug.h and use NSZombie in iPhone SDK

I want to enable NSZombies for my iPhone app.
I have read several articles online and I am still unsure of the exact procedure.
I know I have to set the Environment Variables, which I have done:
NSZombieEnabled = YES
NSDebugEnabled = YES
NSDeallocateZombies = NO
I think (I'm not sure), I have to import NSDebug.h.
When I check the headers of the Foundation Framework in my project, there is no NSDebug.h.
After some research, I found them in the iPhoneSimulator Foundation Framework.
So (and I'm not sure if this is correct), I imported the iPhoneSimualtor Foundation Framework into my project.
I noticed that the file STILL does not show up in the project window, even though I can locate it in the Finder.(Is this normal behavior?).
So I opened up main and added:
#ifdef TARGET_IPHONE_SIMULATOR
#import <Foundation/NSDebug.h>
#endif
I am not sure if that is right either. After this I still can't get the NSZombie to work (unless I have misunderstood what it is supposed to do)
I am expecting to see a log of " NSZombie sent a release... " or something. But I don't see anything
I'm sure I'm just not doing this right, a good step by step would be appreciated.
Thanks
Also of note, I have also enabled:
NSMallocStacklLogging = YES
MallocStackLoggingNoCompact = YES
Are you setting the environment variable correctly? The step by step guide is
Double-click an executable in the Executables group of your Xcode project.
Click the Arguments tab.
In the "Variables to be set in the environment:" section, make a variable called "NSZombieEnabled" and set its value to "YES".
You don't need to #import NSDebug.h
You don't have to include NSDebug.h or import any special frameworks to use NSZombies. Basically, turn 'em on in your environment variables, and then, if you attempt to message a dealloc'd object, THEN you'll see something in your console, along the lines of:
2009-02-10 21:17:08.546 MyApp[16926:20b] *** -[CFString _cfTypeID]: message sent to deallocated instance 0x4babc0
-1 to Apple. Debug builds should be running with full instrumentation out of the box (with a choice to opt-out). Also see http://www.cocoadev.com/index.pl?NSZombieEnabled for additional itms of interest to someone who is developing and debugging a program.