代码:

#import "AppDelegate.h"
#import "RootViewController.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch. RootViewController *rootVC=[[RootViewController alloc]init];
UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:rootVC];
self.window.rootViewController=nav; //将log日志保存到文件
#ifdef BH_DEBUG
[self redirectNSLogToDocumentFolder];
#else #endif self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
} - (void)redirectNSLogToDocumentFolder
{
//如果已经连接Xcode调试则不输出到文件
if(isatty(STDOUT_FILENO)) {
return;
} UIDevice *device = [UIDevice currentDevice];
//在模拟器不保存到文件中
if([[device model] hasSuffix:@"Simulator"]){
return;
} //将NSlog打印信息保存到Document目录下的Log文件夹下
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *logDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Log"]; NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL fileExists = [fileManager fileExistsAtPath:logDirectory];
if (!fileExists) {
[fileManager createDirectoryAtPath:logDirectory withIntermediateDirectories:YES attributes:nil error:nil];
} NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//每次启动后都保存一个新的日志文件中
NSString *dateStr = [formatter stringFromDate:[NSDate date]];
NSString *logFilePath = [logDirectory stringByAppendingFormat:@"/%@.log",dateStr]; //将log输入到文件
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout);
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr); //未捕获的Objective-C异常日志
NSSetUncaughtExceptionHandler (&UncaughtExceptionHandler);
}
void UncaughtExceptionHandler(NSException* exception)
{
NSString* name = [ exception name ];
NSString* reason = [ exception reason ];
NSArray* symbols = [ exception callStackSymbols ];
//异常发生时的调用栈
NSMutableString* strSymbols = [ [ NSMutableString alloc ] init ];
//将调用栈拼成输出日志的字符串
for ( NSString* item in symbols )
{
[strSymbols appendString: item ];
[strSymbols appendString: @"\r\n" ];
} //将crash日志保存到Document目录下的Log文件夹下
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *logDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Log"]; NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:logDirectory]) {
[fileManager createDirectoryAtPath:logDirectory withIntermediateDirectories:YES attributes:nil error:nil];
} NSString *logFilePath = [logDirectory stringByAppendingPathComponent:@"UncaughtException.log"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *dateStr = [formatter stringFromDate:[NSDate date]]; NSString *crashString = [NSString stringWithFormat:@"<- %@ ->[ Uncaught Exception ]\r\nName: %@, Reason: %@\r\n[ Fe Symbols Start ]\r\n%@[ Fe Symbols End ]\r\n\r\n", dateStr, name, reason, strSymbols]; //把错误日志写到文件中
if (![fileManager fileExistsAtPath:logFilePath]) {
[crashString writeToFile:logFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}else{
NSFileHandle *outFile = [NSFileHandle fileHandleForWritingAtPath:logFilePath];
[outFile seekToEndOfFile];
[outFile writeData:[crashString dataUsingEncoding:NSUTF8StringEncoding]];
[outFile closeFile];
} //把错误日志发送到邮箱
// NSString *urlStr = [NSString stringWithFormat:@"mailto://test@163.com?subject=bug报告&body=感谢您的配合!<br><br><br>错误详情:<br>%@",crashString ];
// NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// [[UIApplication sharedApplication] openURL:url];
}

【代码笔记】iOS-将log日志保存到文件的更多相关文章

  1. iOS - NSLog、UncaughtException日志保存到文件

    转:http://blog.csdn.net/marujunyy/article/details/12005767 对于真机,日志没法保存,不好分析问题.所以有必要将日志保存到应用的Docunment ...

  2. logstash自己的日志保存到文件中:log4j2.properties

    status = error dest = err name = PropertiesConfig property.filename = /gwlog/data/logstash/logs appe ...

  3. C# log4net 配置及使用详解--日志保存到文件和Access(转)

    按语: 最近项目要求选用Access数据库,但日志管理采用log4net,但保存到数据库一直没有成功,后按照如下配置在程序退出时可以成功保存. 开始新建文件应用log4net.dll  ,重新编译就报 ...

  4. 学习笔记:The Log(我所读过的最好的一篇分布式技术文章)

    前言 这是一篇学习笔记. 学习的材料来自Jay Kreps的一篇讲Log的博文. 原文很长,但是我坚持看完了,收获颇多,也深深为Jay哥的技术能力.架构能力和对于分布式系统的理解之深刻所折服.同时也因 ...

  5. iOS及时log日志查看工具 (iConsole)

    github下载地址:https://github.com/nicklockwood/iConsole 偶然看到的一个iOS及时log日志查看工具,通过该工具,我们可以在任何想看日志的时候,通过手势呼 ...

  6. 【hadoop代码笔记】Mapreduce shuffle过程之Map输出过程

    一.概要描述 shuffle是MapReduce的一个核心过程,因此没有在前面的MapReduce作业提交的过程中描述,而是单独拿出来比较详细的描述. 根据官方的流程图示如下: 本篇文章中只是想尝试从 ...

  7. IOS开发笔记 IOS如何访问通讯录

    IOS开发笔记  IOS如何访问通讯录 其实我是反对这类的需求,你说你读我的隐私,我肯定不愿意的. 幸好ios6.0 以后给了个权限控制.当打开app的时候你可以选择拒绝. 实现方法: [plain] ...

  8. [学习笔记] SSD代码笔记 + EifficientNet backbone 练习

    SSD代码笔记 + EifficientNet backbone 练习 ssd代码完全ok了,然后用最近性能和速度都非常牛的Eifficient Net做backbone设计了自己的TinySSD网络 ...

  9. iOS crash log 解析 symbol address = stack address - slide 运行时获取slide的api 利用dwarfdump从dsym文件中得到symbol

    概述: 为什么 crash log 内 Exception Backtrace 部分的地址(stack address)不能从 dsym 文件中查出对应的代码? 因为 ASLR(Address spa ...

随机推荐

  1. 了解SpringMVC框架及基本工作流程

    传统原生的JSP+Servlet在开发上过程上虽然简单明了,JSP页面传递数据到Servlet,Servlet整理数据(逻辑开发)或者从数据库提取数据接着再转发到JSP页面上,但是其似乎只能止步于此, ...

  2. Android Studio添加PNG图片报错原因

    今天在网上看到一个关于Splash Activity的Android帖子,博主在一通讲解之后也给出了代码.于是果断下载下来了看看怎么实现的.一步步照着流程把这个功能实现了一遍.一切都没有大问题,但是在 ...

  3. C# 6.0的字典(Dictionary)的语法

    在C# 6.0,当我们使用Dictionary时,我们可以使用新语法,来去简化程序以提高效率. public Dictionary<string, object> OldToolLocat ...

  4. MVC的路径查找顺序

    使用MVC的朋友们,知道MVC的funny之处. 但是如果出现路径找不到,请记住以下的页面路径寻找顺序. http://www.cnblogs.com/sosoft/ 首先,知道你的Controlle ...

  5. JS通过身份证号码获取出生年月日

    这里我们讲述一下关于jq根据身份证号码计算出生日期.年龄.性别,有需要的同学可参考一下.    代码如下 复制代码 //获取输入身份证号码 var UUserCard = $("#UUser ...

  6. 用python生成一个导出数据库的bat脚本文件

    # 环境: python3.x def getExportDbSql(db, index): # 获取导出一个数据库实例的sql语句 sql = 'mysqldump -u%s -p%s -h%s - ...

  7. 优秀ASP.NET程序员修炼之路

    初级的程序员或经验不足的程序员往往只意识到自己的程序是写给计算机的,而不会在意程序其实也是写给人的,或在意得不够.不全面. 写给机器的程序,往往追求的是运行正确.执行效率能满足要求.但程序员的任务仅仅 ...

  8. iOS版本比较方法

    之前一直把版本号转换为floatValue,但是最近在项目中又出现了float的问题,主要是 NSString表示为@"17.30",转换为floatValue 值为17.2999 ...

  9. HTTPS能有效保护用户隐私

    HTTPS就等于HTTP加上TLS(SSL),HTTPS协议的目标主要有三个: http://hovertree.com/menu/webfront/ 数据保密性.保证内容在传输过程中不会被第三方查看 ...

  10. C#使用Process调用批处理阻塞问题

    PS:又见到熟悉的C#代码了,好开心,哈哈哈.这次又跳坑了,好不容易才爬起来.   公司有自己开发的一套Submit.Compile.Publish的生命周期系统. 在Compile时,需要调用外部的 ...