Skip to content

Instantly share code, notes, and snippets.

@olegam
Last active August 29, 2015 13:57
Show Gist options
  • Save olegam/9545390 to your computer and use it in GitHub Desktop.
Save olegam/9545390 to your computer and use it in GitHub Desktop.
NSLog tweak to create a clickable link to the file and line that created the log output. Short and concise format to fit on a single line in most cases.

Sometimes it can be hard to figure out where log statements in the console come from. With this tweak you get log output like this:

11:03:12.257 : User logged in with username: olegam (FIBAPIClient.m:507)

Because of AppCode awesomeness the FileName:LineNumber part will be clickable and take you right to the code that produced the log statement. To get this in your own project you should:

  1. Redefine NSLog in your prefix.pch file
#define NSLog(format,...) SHPLogFunction(format, [@""__FILE__ lastPathComponent], __LINE__, ##__VA_ARGS__);
  1. Implement the following functions in a .m file imported by Prefix.pch
NSDateFormatter *ThreadLocalLogDateFormatter() {
    NSMutableDictionary *threadCache = [[NSThread currentThread] threadDictionary];
    NSDateFormatter *df = threadCache[@"SHPLOG_DATE_FORMATTER"];
    if (!df) {
        df = [[NSDateFormatter alloc] init];
        df.dateFormat = @"HH:mm:ss.SSS";
        threadCache[@"SHPLOG_DATE_FORMATTER"] = df;
    }
    return df;
}

void SHPLogFunction(NSString *format, NSString *file, NSUInteger line, ...) {
    NSDateFormatter *df = ThreadLocalLogDateFormatter();
    NSString *timeStr = [df stringFromDate:[NSDate date]];

    va_list args;
    va_start(args, format);
    NSString *logStr = [[NSString alloc] initWithFormat:format arguments:args];
    NSString *withTimeStr = [[NSString alloc] initWithFormat:@"%@ : %@ (%@:%d)", timeStr, logStr, file, line];
    CFShow((__bridge CFStringRef)withTimeStr);
    va_end(args);
}

This solution was developed after a discussion on Youtrack: http://youtrack.jetbrains.com/issue/OC-6808

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment