Filename and Line Number with NSLog: Part I

Coming from a C development background, long before the days of integrated debuggers, printf() was the primary tool for tracking down bugs. Building on that, NSLog is no doubt helpful. However, as the amount of code in a project grows, I often find that another reference point in the output would be helpful, namely, the filename and line number where the NSLog calls originate.

This is a two part series on creating a new class that wraps NSLog to add several additional debugging features including output of the filename/path, line number information and the option to turn debug messages off/on.

In this post I want to show you how to call the code, and in the next, I’ll show the class I wrote to make this happen. The code below shows how easy it is to call the debug function.

1
2
3
4
5
  SomeClass *ptr = [[SomeClass alloc] initWithStrAndDate:@"Fubar" date:[NSDate date]];
  NSString *str = [[NSString alloc] initWithString:@"Test string"];
  int x = 99;
 
  debug(@"ptr:%@ x:%d str:%@", ptr, x, str);

Notice how I have a mix of a “custom” class (SomeClass), a built-in class (NSString) and a native C type (int). The debug statement accepts parameters in the same format as NSLog, that is, a format string followed by the arguments. The output of this example is shown below.

NSLog outputs the timestamp and the process ID, the debug method appends to this the current filename and line number information where NSLog was called from.

I’ve also added an option to display the fullpath for the file name. See the figure below, which is the same code as above, with the configuration option for showing the full path set to true.

In the next post I’ll walk you through the code to create this debug function. I’ll also include the Xcode project file so you can mess with it as you like.

  1. Coming from a long time Java background, I have found log files on the server using “log4j” especially helpful. Is there a “log4 objective c” library that one could use out there? In that, there ways to format line numbers, module and class names and exception messages. This is often helpful when maintaining systems.

    Thanks.

  2. Hi everybody,

    I normally use this stuff from plain C, which is translated by the preprocessor:

    NSLog(@”[%s:%s:%d] Here i am”,__FUNCTION__,__FILE__,__LINE__);

    One can easily write a macro (e.g. myNSLog) for this to insert it automatically.

  3. i wish nslog could let some one easily
    log to a file. (rotate log files etc.)
    allow for levels, based on say class name or something.

    in the past i have rolled my own logger inspired by the java log4

Comments are closed.