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

Recruit two powerful-sounding students t...
I am a fan of anime, and I hear about a lot that comes through, but one that escaped my attention until now is A Certain Scientific Railgun T, and that name is very enticing. If it's new to you too, then players of Blue Archive can get a hands-on... | Read more »
Top Hat Studios unveils a new gameplay t...
There are a lot of big games coming that you might be excited about, but one of those I am most interested in is Athenian Rhapsody because it looks delightfully silly. The developers behind this project, the rather fancy-sounding Top Hat Studios,... | Read more »
Bound through time on the hunt for sneak...
Have you ever sat down and wondered what would happen if Dr Who and Sherlock Holmes went on an adventure? Well, besides probably being the best mash-up of English fiction, you'd get the Hidden Through Time series, and now Rogueside has announced... | Read more »
The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »

Price Scanner via MacPrices.net

May 2024 Apple Education discounts on MacBook...
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
Clearance 16-inch M2 Pro MacBook Pros in stoc...
Apple has clearance 16″ M2 Pro MacBook Pros available in their Certified Refurbished store starting at $2049 and ranging up to $450 off original MSRP. Each model features a new outer case, shipping... Read more
Save $300 at Apple on 14-inch M3 MacBook Pros...
Apple has 14″ M3 MacBook Pros with 16GB of RAM, Certified Refurbished, available for $270-$300 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year warranty is... Read more
Apple continues to offer 14-inch M3 MacBook P...
Apple has 14″ M3 MacBook Pros, Certified Refurbished, available starting at only $1359 and ranging up to $270 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year... Read more
Apple AirPods Pro with USB-C return to all-ti...
Amazon has Apple’s AirPods Pro with USB-C in stock and on sale for $179.99 including free shipping. Their price is $70 (28%) off MSRP, and it’s currently the lowest price available for new AirPods... Read more
Apple Magic Keyboards for iPads are on sale f...
Amazon has Apple Magic Keyboards for iPads on sale today for up to $70 off MSRP, shipping included: – Magic Keyboard for 10th-generation Apple iPad: $199, save $50 – Magic Keyboard for 11″ iPad Pro/... Read more
Apple’s 13-inch M2 MacBook Airs return to rec...
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 currently... Read more
Best Buy is clearing out iPad Airs for up to...
In advance of next week’s probably release of new and updated iPad Airs, Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices for up to $200 off Apple’s MSRP, starting at $399. Sale prices... Read more
Every version of Apple Pencil is on sale toda...
Best Buy has all Apple Pencils on sale today for $79, ranging up to 39% off MSRP for some models. Sale prices for online orders only, in-store prices may vary. Order online and choose free shipping... Read more
Sunday Sale: Apple Studio Display with Standa...
Amazon has the standard-glass Apple Studio Display on sale for $300 off MSRP for a limited time. Shipping is free: – Studio Display (Standard glass): $1299.97 $300 off MSRP For the latest prices and... Read more

Jobs Board

Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
*Apple* App Developer - Datrose (United Stat...
…year experiencein programming and have computer knowledge with SWIFT. Job Responsibilites: Apple App Developer is expected to support essential tasks for the RxASL 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
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
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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.