Developer to Developer: Logging with a Purpose
Volume Number: 26
Issue Number: 12
Column Tag: Developer to Developer
Developer to Developer: Logging with a Purpose
A look at logging techniques in Objective-C applications
by Boisy G. Pitre
Introduction
As this article is being written, I've just returned from attending the 2010 MacTech Conference in Los Angeles, and can't say enough about how informative and well put together the event was. I particularly enjoyed meeting many of the attendees, both in the developer and IT tracks. The sessions were rich with valuable information and insights from the speakers. Take it from me, if you could not make the conference this year, I highly recommend that you make preparations to attend the next conference. Ed, Neil, and the rest of the MacTech folks did a tremendous job.
One of the sessions at the conference was given by Mark Dalrymple; it was simply entitled "Thoughts On Debugging." I found Mark's insights and experience very closely paralleled my own, especially when it comes to "caveman debugging." The philosophy on this type of debugging emphasizes the use of printf and other logging functions to both debug a program and to learn how it works by examination. The caveman aspect harkens to the fact that the developer chooses a seemingly more primitive way to catch bugs, by using logging instead of a debugger like GDB.
For this month's Developer to Developer, we'll examine logging, its applicability to debugging, and how we can take advantage of this technique to make better applications. We will then introduce a logging class that has been created and used in our own software development process here at Tee–Boy.
In The Beginning Was the Log...
Before interactive debuggers came on the scene, debugging running code was most easily accomplished by the addition of one or more output statements that could demonstrate the value of a variable at some point in the program. These statements found themselves on paper and embedded in the phosphor of amber and green terminals in days past. Even now, this ancient (in computer terms) technique still holds a great deal of value when attempting to find certain problems in our code.
Take for instance, a particularly tricky race condition in a multithreaded application that manifests itself once every 200 runs or so. Trying to pinpoint the problem using an interactive debugger could be a time-consuming task. There is the setting up of the program in the debugger itself, the setting of breakpoints in various places that are suspect, and the time spent waiting for the problem to show up. By its very nature, interactive debugging is interactive. It requires the developer to be present in order to move the flow of the program forward. When a bug manifests itself sporadically, and the exact scenario to reproduce it is uncertain, logging can often be the best recourse for resolution of the issue.
Besides being the most ubiquitous way to debug, log statements also have another advantage: they can act as a record of a program's actions while it was running. We can use logs as an audit trail to see the exact flow of the code. We can add additional value to the log output by adding the current date and time to each log statement so that we can determine the timing at various points in our program. Measuring the relative time that it takes between one log statement to the next can yield clues about how our program is running, and whether or not there may be problems ahead.
Basic Logging
As programmers, we like to get things done quickly, and that includes our debugging sessions. Oftentimes, you may find yourself in a hurry to find a particular problem, and stick a logging statement somewhere in your code. Then later, when the issue is fixed, you may forget to remove the statement, and that finds its way into production. This minimalist approach to logging is fine as long as you can remember to remove these logging statements before letting loose your product to the world. Of course, if there is little or no value for the logging statements to remain in a production version of your program, you are left with the task of having to remove them before a code freeze.
A solution to this problem that is often taken is to use a program-wide macro that will switch on and off debugging and logging statements by wrapping conditionals around them:
#ifdef DEBUG
NSLog(@"Debug statement here");
#endif
This approach works quite well on a small scale, but can get messy as well as tie up your time typing needless conditional statements over and over again for each logging line. A better approach would be to define a special macro which, when used in your code, would generate logging statements without requiring the wrapping of each statement in the conditional.
We can improve on the previous process by incorporating a macro/function based approach to logging in our programs. This will require a function that we will call DebugLog. The following code demonstrates how this can be done. When the ENABLE_LOGGING macro is defined, then the DebugLog function uses C's variable arguments functions to output any logging to the standard output path. If the ENABLE_LOGGING macro is not defined, then DebugLog resolves to a do-nothing function, and logging is simply ignored.
#include <stdio.h>
#include <stdarg.h>
#ifdef ENABLE_LOGGING
void DebugLog(char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
}
#else
void DebugLog (char *fmt, ...)
{
}
#endif
By defining ENABLE_LOGGING in a global header file, such as your application's prefix header, you can get the benefit of logging at anytime and turn it off with a simple switch. Your source files remain the same; there are no #ifdef/#endif conditional wrappers to litter your source either. As a result, your code looks a lot cleaner.
Smarter Logging With the TBLog Class
The function based approach above makes interspersed logging code in our source look a lot neater than with the macro wrapping approach. However, it has a few shortcomings. First, it still requires a conditional to be set or cleared in order to turn on or off logging. Additionally, each logging statement is on equal footing; there is no way to prioritize logging statements. In many cases, we don't want to totally suppress logging, but may want minimal logging. Yet at other times we want verbose logging, or even a mix of the two.
Enter the TBLog class, an Objective-C class which brings all of these benefits to your code. Not only do we avoid wrapping conditionals, but we also get logging prioritization, plus some other benefits. The code for this class is available on the MacTech FTP site at ftp://ftp.mactech.com.
The TBLog class is a singleton class, meaning that for each application, only one actual instance of the class exists. This design pattern reinforces the notion that logging is a unified and arbitrated process in your application. In order to perform logging, we obtain the shared log object, then we send the log:level: message to that object with our logging message:
[[TBLog sharedLog] log:@"Logging message" level:TBLogLevelInfo];
With TBLog's log:level: message, we get several features "for free" including the current date and time automatically prepended to the message, as well as multiple output options for the message itself.
The first parameter is obviously the message to log, but the second parameter needs some explaining. As we noted with the macro/function based approach, there is no ranking of a log message's importance; all log lines are on equal footing. What the log level does is gives us fine grained control over which log messages are actually logged and which ones aren't.
The TBLog class provides five logging levels, and they are defined in the following table:
Log Level Name Usage
TBLogLevelNone No logging occurs
TBLogLevelInfo Logging for informational purposes
TBLogLevelDetailed Logging for more detailed informational purposes
TBLogLevelError Logging when an error occurs
TBLogLevelDebug Logging for debugging purposes
(highest setting)
Each level is progressively more critical in terms of priority. The lowest value, TBLogLevelNone simply suppresses that log line completely; all other levels will allow the debugging message to pass through to the console, depending upon the log level setting.
The log level setting is a global filter, dictating which messages will pass through the logging system. Since the TBLog class is a singleton class, this log setting affects the entire program. It can be set as follows:
[[TBLog sharedLog] setLogLevel:TBLogLevelDetailed];
In this case, any call to log:level: with a log level of TBLogLevelDetailed, TBLogLevelError or TBLogLevelDebug will pass its message onto the logging system. Any log message with a lower level will be suppressed. The log level can be set at any time in the program, giving you the option to see more detail when you want, or less detail. As you layout your logging in your program, you should be mindful as to which level is paired with each message. Is the message for informational purposes? If so, then it should probably be seen more often than a message that is intended for debugging. Laying out your logging strategy with these log levels and setting logging programmatically gives you a great degree of flexibility.
Another area where the TBLog class brings convenience is where the actual logging appears. For Cocoa applications, the NSLog() function is typically used, and its output is directed to the system console. The TBLog class does allow logging to the console; it also provides logging to an NSTextView object, as we'll see shortly.
By default, logging to the console is turned off. Turning on logging to the console can be achieved by turning on that specific feature with the following line:
[[TBLog sharedLog] setLogToConsole:TRUE];
Depending upon your application, you may find it useful to have a visual log which is based on the NSTextView object. This feature is built right into TBLog, and simply requires you to identify the view for logging. For example, here's how to set up logging to an NSTextView object named someTextView:
[[TBLog sharedLog] setTextView:someTextView];
An examination of the setText: code reveals that a check for what thread we are running on is made. If we are not running on the main thread when the log:level: method is called, then we use the performSelectorOnMainThread:withObject: method to update the NSTextView. By design, Cocoa applications should only update UI components on the main thread.
If you decide at some point to turn off logging to the NSTextView, this feature can be turned off by passing nil:
[[TBLog sharedLog] setTextView:nil];
Another important addition to the TBLog class is a convenient macro, TBLogFormat(), that allows you to use printf-style variable arguments:
[[TBLog sharedLog] log:TBLogFormat(@"Logging message with param %d", x) level:TBLogLevelInfo];
Ready to explore? The LogTest project, available on the MacTech FTP site, is a small Cocoa application that demonstrates the use of TBLog in an interactive manner. I highly recommend that you study the source for this project, as well as the TBLog.h header file for additional methods that you can use to determine the log level, console output state, and other features. You can also improve the design by adding other logging output options, such as to a custom file. Perhaps you would like a different set of logging levels. Feel free to extend, modify and incorporate it into your applications.
A Cautionary Note
Logging is good, but like anything else in life, too much of a good thing can be the very thing that causes us grief. Be aware that overzealous logging may end up slowing down your application in critical areas. It is not unusual in time critical areas of the code for logging to exacerbate or even mask a problem. There have been many times that I have seen this in action: just removing a set of log statements would change the behavior of a program. In general, this type of voodoo only happens with very specific time sensitive applications. Your Cocoa applications should be able to accommodate a decent amount of logging for the most part. Just be aware of this caveat.
Another consideration is the size of the log file. A copious amount of logging can fill up log files quite fast. OS X does a good job of housekeeping in this area by periodically archiving its logs. However, if you decide to extend TBLog to update your own log file, be aware of the amount of logging that you are doing, and have a contingency plan in place to deal with large log files.
Summary
Despite its seemingly archaic heritage, logging remains an integral part of the software development process, and in some cases is the best option for seeking out bugs. It gives us some verification that our application is working correctly (or incorrectly), and also conveys code flow information. The importance of logging in applications extends beyond just debugging. It can be used to provide a record of actions of a program on a system that can be used for feedback. Now with TBLog, you have the foundation for a flexible and adaptable logging system that can make debugging and auditing of your application easier
Bibliography and References
CocoaDev.com, NSLog, http://www.cocoadev.com/index.pl?NSLog
Mark Dalrymple, Links to the MacTech talk, "Thoughts on Debugging", http://borkwarellc.wordpress.com/2010-/11/04/links-from-my-mactech-talk/
Boisy G. Pitre lives in Southwest Louisiana and is the lead developer at Tee-Boy where he also consults on Mac and iOS projects with a variety of clients. He holds a Master of Science in Computer Science from the University of Louisiana at Lafayette. Besides Mac programming, his hobbies and interests include retro-computing, ham radio, vending machine and arcade game restoration, and playing Cajun music. You can reach him at boisy@tee-boy.com.