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

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.