【代码笔记】iOS-将log日志保存到文件
代码:

#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日志保存到文件的更多相关文章
- iOS - NSLog、UncaughtException日志保存到文件
转:http://blog.csdn.net/marujunyy/article/details/12005767 对于真机,日志没法保存,不好分析问题.所以有必要将日志保存到应用的Docunment ...
- logstash自己的日志保存到文件中:log4j2.properties
status = error dest = err name = PropertiesConfig property.filename = /gwlog/data/logstash/logs appe ...
- C# log4net 配置及使用详解--日志保存到文件和Access(转)
按语: 最近项目要求选用Access数据库,但日志管理采用log4net,但保存到数据库一直没有成功,后按照如下配置在程序退出时可以成功保存. 开始新建文件应用log4net.dll ,重新编译就报 ...
- 学习笔记:The Log(我所读过的最好的一篇分布式技术文章)
前言 这是一篇学习笔记. 学习的材料来自Jay Kreps的一篇讲Log的博文. 原文很长,但是我坚持看完了,收获颇多,也深深为Jay哥的技术能力.架构能力和对于分布式系统的理解之深刻所折服.同时也因 ...
- iOS及时log日志查看工具 (iConsole)
github下载地址:https://github.com/nicklockwood/iConsole 偶然看到的一个iOS及时log日志查看工具,通过该工具,我们可以在任何想看日志的时候,通过手势呼 ...
- 【hadoop代码笔记】Mapreduce shuffle过程之Map输出过程
一.概要描述 shuffle是MapReduce的一个核心过程,因此没有在前面的MapReduce作业提交的过程中描述,而是单独拿出来比较详细的描述. 根据官方的流程图示如下: 本篇文章中只是想尝试从 ...
- IOS开发笔记 IOS如何访问通讯录
IOS开发笔记 IOS如何访问通讯录 其实我是反对这类的需求,你说你读我的隐私,我肯定不愿意的. 幸好ios6.0 以后给了个权限控制.当打开app的时候你可以选择拒绝. 实现方法: [plain] ...
- [学习笔记] SSD代码笔记 + EifficientNet backbone 练习
SSD代码笔记 + EifficientNet backbone 练习 ssd代码完全ok了,然后用最近性能和速度都非常牛的Eifficient Net做backbone设计了自己的TinySSD网络 ...
- iOS crash log 解析 symbol address = stack address - slide 运行时获取slide的api 利用dwarfdump从dsym文件中得到symbol
概述: 为什么 crash log 内 Exception Backtrace 部分的地址(stack address)不能从 dsym 文件中查出对应的代码? 因为 ASLR(Address spa ...
随机推荐
- 基于HTML5技术的电力3D监控应用(一)
最近参与了国网计量中心的四线一库自动化检定系统的项目开发,团队封闭开发了大半年终于快到尾声了,整个项目过程实在非常累,我的mentor杨杨老师是这样描述的:累的不想说话了.我估计是我太渴望新知识,整天 ...
- js简单实现div宽度匀速增加/减小
效果类似百度首页音乐盒. 点击音乐右边的div可以变长或者变短. 代码: <!DOCTYPE html> <html lang="en"> <head ...
- C#将集合快速排序
C#实现集合排序类. 说明: 1.集合类型参数化: 2.可根据集合中的对象的各个属性进行排序,传入属性名称即可: 注:属性必须实现了IComparable接口,C#中int.datetime.stri ...
- 使用powerdesigner创建数据库表
(1 )新建概念模型 (2 )新建表,添加表各个属性 填写属性名称和类型,主键要勾选上P,M,D. (3) 如何各个表中有相同的字段名,需要设置Tool->Model Options,把红色区域 ...
- .Net(C#)最简单的邮件发送案例
一.序言 刚开始接触邮件发送功能的时候,在网上找的资料都挺复杂的!对于新手入门有点难(至少对于本人来说,第一次接触的时候确实不容易).这里就写一段简单的邮箱发送代码,备忘,也给新手一个参考(相关类的字 ...
- JsonConvert 使用注意事项之 Serializable
1.使用NuGet安装Newtonsoft.Json. 2.创建需要序列化的类. public class Person { public string Name{get;set;} public i ...
- hibernate---注解--CascadeType属性
cascade表示级联操作 CascadeType.MERGE级联更新:若items属性修改了那么order对象保存时同时修改items里的对象.对应EntityManager的merge方法 Cas ...
- hibernate----1-1
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hi ...
- python 三级菜单
三级列表: menu = { '北京':{ '海淀':{ '五道口':{ 'soho':{}, '网易':{}, 'google':{} }, '中关村':{ '爱奇艺':{}, '汽车之家':{}, ...
- Java继承中成员方法的overload(重载/过载)
如果Java基础类有一个方法名被"过载"使用多次,在衍生类里对那个方法名的重新定义就不会隐藏任何基础类的版本.所以无论方法在这一级还是在一个基础类中定义,过载都会生效. publi ...