Blog

Logging with POCO on iOS

The POCO C++ Libraries come with a powerful logging framework that supports different logging channels like log files, console, syslog or the Windows Event Log. All of these channels (except maybe the FileChannel) are not very useful when developing applications for the iPhone. So what should one do when porting existing C++ code that uses the POCO logging framework to the iPhone? Wouldn't it be nice to see the logging output in the Xcode debugger's output window? As easy as pie! Since the POCO logging framework is extensible with new channel types, we simply create a new Channel class that uses the iOS NSLog() function. We'll call the new class NSLogChannel. The implementation is just a few lines of code. We create a new subclass of Poco::Channel and override the log() member function. The header file for NSLogChannel is shown below:

/* * NSLogChannel.h * */ #ifndef NSLogChannel_INCLUDED #define NSLogChannel_INCLUDED #include "Poco/Channel.h" class NSLogChannel: public Poco::Channel { public: void log(const Poco::Message& msg); }; #endif // NSLogChannel_INCLUDED

In the log() method, we just call NSLog(), passing int he message source and text. We could actually omit the message source and use a FormattingChannel to format the log message prior to passing it to the channel, but we'll keep things simple.

/* * NSLogChannel.cpp * */ #include "NSLogChannel.h" #include "Poco/Message.h" #import <Foundation/Foundation.h> void NSLogChannel::log(const Poco::Message& msg) { NSLog(@"%s: %s", msg.getSource().c_str(), msg.getText().c_str()); }

Now that we have the NSLogChannel class, we need to register it with the logging framework. A good place to do this is the application's main() function. We're going to mix Objective-C and C++ code in the same file, so the file containing the main() function should have the extension ".M" (note the uppercase M), so Xcode will compile the file as Objective-C++.

#import <UIKit/UIKit.h> #import "NSLogChannel.h" #import "Poco/Logger.h" int main(int argc, char *argv[]) { Poco::Logger::root().setChannel(new NSLogChannel); NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, nil); [pool release]; return retVal; }

That's it. Everything logged using the POCO logging framework will now appear in the debug output in Xcode.

Posted in POCO C++ Libraries, Tips & Tricks
Tagged , , ,
Questions or comments? Contact us!