1. 添加库文件
ExceptionHandling.framework
2. 在 applicationDidFinishLaunching
添加
//add the excepiton catch
[[NSExceptionHandler defaultExceptionHandler] setExceptionHandlingMask:NSLogAndHandleEveryExceptionMask];
[[NSExceptionHandler defaultExceptionHandler] setDelegate:self];
3. 实现方法
- (BOOL)exceptionHandler:(NSExceptionHandler *)sender shouldLogException:(NSException *)exception mask:(NSUInteger)aMask {
[self printStackTrace:exception];
return YES;
}
- (BOOL)exceptionHandler:(NSExceptionHandler *)sender shouldHandleException:(NSException *)exception mask:(NSUInteger)aMask {
NSLog(@"printStackTrace: %@", [exception reason]);
return YES;
}
4. 打印日志
- (void)printStackTrace:(NSException *)e
{
NSString *stack = [[e userInfo] objectForKey:NSStackTraceKey];
if (stack) {
NSTask *ls = [[NSTask alloc] init];
NSString *pid = [[NSNumber numberWithInt:[[NSProcessInfo processInfo] processIdentifier]] stringValue];
NSMutableArray *args = [NSMutableArray arrayWithCapacity:20];
[args addObject:@"-p"];
[args addObject:pid];
[args addObjectsFromArray:[stack componentsSeparatedByString:@" "]];
// Note: function addresses are separated by double spaces, not a single space.
[ls setLaunchPath:@"/usr/bin/atos"];
[ls setArguments:args];
NSPipe *pipe;
pipe = [NSPipe pipe];
[ls setStandardOutput: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[ls launch];
NSData *data;
data = [file readDataToEndOfFile];
NSString *string;
string = [[NSString alloc] initWithData: data
encoding: NSUTF8StringEncoding];
NSString *strFormat = [NSString stringWithFormat:@"\n\n*************************exception begin\nexception time: %@\n%@\n*************************exception end\n\n",[NSDate date] ,string];
NSLog(@"printStackTrace: %@", strFormat);
} else {
NSLog(@"No stack trace available.");
}
}