Using Objective C to read log messages posted to the device console Using Objective C to read log messages posted to the device console ios ios

Using Objective C to read log messages posted to the device console


This entry in the Cocoanetics blogs has sample code to access the system log on iOS using the ASL (Apple System Logger) API (man page):

aslmsg q, m;int i;const char *key, *val;q = asl_new(ASL_TYPE_QUERY);aslresponse r = asl_search(NULL, q);while (NULL != (m = aslresponse_next(r))){    NSMutableDictionary *tmpDict = [NSMutableDictionary dictionary];    for (i = 0; (NULL != (key = asl_key(m, i))); i++)    {        NSString *keyString = [NSString stringWithUTF8String:(char *)key];        val = asl_get(m, key);        NSString *string = [NSString stringWithUTF8String:val];        [tmpDict setObject:string forKey:keyString];    }    NSLog(@"%@", tmpDict);}aslresponse_free(r);

Note that you need to poll ASL to read the latest messages. The code above will also fail when ran on the iPhone simulator, but works just fine on an actual device.

If you don't want to fight the C ASL API, have a look at this Objective-C wrapper called ASLogger.


As of IOS 7, this method won't work any more. Apple removed access to ASL due to security reason.


Here's a Swift implementation if anyone's looking for one:

static func systemLogs() -> [[String: String]] {    let q = asl_new(UInt32(ASL_TYPE_QUERY))    var logs = [[String: String]]()    let r = asl_search(nil, q)    var m = asl_next(r)    while m != nil {        var logDict = [String: String]()        var i: UInt32 = 0        while true {            if let key = String.fromCString(asl_key(m, i)) {                let val = String.fromCString(asl_get(m, key))                logDict[key] = val                i++            } else {                break            }        }        m = asl_next(r)        logs.append(logDict)    }    asl_release(r)    return logs}


matomo