您的位置:首页 > 移动开发 > IOS开发

IOS下捕获异常并生成异常堆栈日志

2014-10-11 14:47 393 查看
在appDidFinishLaunching函数中添加:
NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
[self addSigaction];

添加函数:
void UncaughtExceptionHandler(NSException *exception)
{
NSArray *storeFilePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *doucumentsDirectiory = [storeFilePath objectAtIndex:0];

//crashReport path
NSString *carshReportPath = [doucumentsDirectiory stringByAppendingPathComponent:@"CrashReport.txt"];
NSArray *callStack = [exception callStackSymbols];  //exception callStack
NSString *name = [exception name];                  //exception name
NSString *reason = [exception reason];              //exception reason
NSString *strUrl = [NSString stringWithFormat:@"Exception Name:\n%@\nException Reason:\n%@\nCallStackSymbols:\n%@",name,reason,[callStack componentsJoinedByString:@"\n"]];
//write
if([strUrl rangeOfString:@"[ZIosEnv performSelector:]"].location == NSNotFound)
{
[strUrl writeToFile:carshReportPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
}

- (void)addSigaction
{
    //对于用NSSetUncaughtExceptionHandler不能捕获的异常利用unix标准的signal机制处理
    struct sigaction mySigAction;
    mySigAction.sa_sigaction = stacktrace;
    mySigAction.sa_flags = SA_SIGINFO;
    
    sigemptyset(&mySigAction.sa_mask);
    sigaction(SIGQUIT, &mySigAction, NULL);
    sigaction(SIGILL , &mySigAction, NULL);
    sigaction(SIGTRAP, &mySigAction, NULL);
    sigaction(SIGABRT, &mySigAction, NULL);
    sigaction(SIGEMT , &mySigAction, NULL);
    sigaction(SIGFPE , &mySigAction, NULL);
    sigaction(SIGBUS , &mySigAction, NULL);
    sigaction(SIGSEGV, &mySigAction, NULL);
    sigaction(SIGSYS , &mySigAction, NULL);
    sigaction(SIGPIPE, &mySigAction, NULL);
    sigaction(SIGALRM, &mySigAction, NULL);
    sigaction(SIGXCPU, &mySigAction, NULL);
    sigaction(SIGXFSZ, &mySigAction, NULL);
}

添加头文件:
#include <signal.h>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息