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

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
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
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and 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.