TweetFollow Us on Twitter

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.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »
Play Together teams up with Sanrio to br...
I was quite surprised to learn that the massive social network game Play Together had never collaborated with the globally popular Sanrio IP, it seems like the perfect team. Well, this glaring omission has now been rectified, as that instantly... | Read more »
Dark and Darker Mobile gets a new teaser...
Bluehole Studio and KRAFTON have released a new teaser trailer for their upcoming loot extravaganza Dark and Darker Mobile. Alongside this look into the underside of treasure hunting, we have received a few pieces of information about gameplay... | Read more »
DOFUS Touch relaunches on the global sta...
After being a big part of a lot of gamers - or at the very least my - school years with Dofus and Wakfu, Ankama sort of shied away from the global stage a bit before staging a big comeback with Waven last year. Now, the France-based developers are... | Read more »

Price Scanner via MacPrices.net

Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more
B&H has 16-inch MacBook Pros on sale for...
Apple 16″ MacBook Pros with M3 Pro and M3 Max CPUs are in stock and on sale today for $200-$300 off MSRP at B&H Photo. Their prices are among the lowest currently available for these models. B... Read more
Updated Mac Desktop Price Trackers
Our Apple award-winning Mac desktop price trackers are the best place to look for the lowest prices and latest sales on all the latest computers. Scan our price trackers for the latest information on... Read more
9th-generation iPads on sale for $80 off MSRP...
Best Buy has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80 off MSRP on their online store for a limited time. Prices start at only $249. Sale prices for online orders only, in-store prices... Read more
15-inch M3 MacBook Airs on sale for $100 off...
Best Buy has Apple 15″ MacBook Airs with M3 CPUs on sale for $100 off MSRP on their online store. Prices valid for online orders only, in-store prices may vary. Order online and choose free shipping... Read more
24-inch M3 iMacs now on sale for $150 off MSR...
Amazon is now offering a $150 discount on Apple’s new M3-powered 24″ iMacs. Prices start at $1149 for models with 8GB of RAM and 256GB of storage: – 24″ M3 iMac/8-core GPU/8GB/256GB: $1149.99, $150... Read more
15-inch M3 MacBook Airs now on sale for $150...
Amazon is now offering a $150 discount on Apple’s new M3-powered 15″ MacBook Airs. Prices start at $1149 for models with 8GB of RAM and 256GB of storage: – 15″ M3 MacBook Air/8GB/256GB: $1149.99, $... Read more
The latest Apple Education discounts on MacBo...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take up to $300 off the purchase of a new MacBook... Read more

Jobs Board

Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Retail Assistant Manager- *Apple* Blossom Ma...
Retail Assistant Manager- APPLE BLOSSOM MALL Brand: Bath & Body Works Location: Winchester, VA, US Location Type: On-site Job ID: 04225 Job Area: Store: Management Read more
Housekeeper, *Apple* Valley Village - Cassi...
Apple Valley Village Health Care Center, a senior care campus, is hiring a Part-Time Housekeeper to join our team! We will train you for this position! In this role, Read more
Sonographer - *Apple* Hill Imaging Center -...
Sonographer - Apple Hill Imaging Center - Evenings Location: York Hospital, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now See Read more
Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.