iOS日志本地化--日志重定向

写在前面

本文主要是给读者分享技术的,如何保存能控制台输出的log,以便于查找程序本身出现的问题。

我们该如何做

首先

我们要判断,是不是模拟器

1
2
3
4
5
6
7
#if !(TARGET_IPHONE_SIMULATOR)//真机
//连接xcode时可以从监视器中看日志 没连接时Log日志会输出到文件中,
[self redirectNSLogToDocumentFolder];
NSLog(@"真机");
#else//模拟器
NSLog(@"模拟器");
#endif
其次

我们还要接着判断是不是真机连接了Xcode,然后才开始进行日志本地化文件的生成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
- (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]];
self.filepath = [logDirectory stringByAppendingFormat:@"/%@.log",dateStr];
// 将log输入到文件
freopen([self.filepath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout);
freopen([self.filepath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
//未捕获的Objective-C异常日志
NSSetUncaughtExceptionHandler (&UncaughtExceptionHandler);
}
最后

这是一个报错的异常信息,也就是我们所说的崩溃信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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"];
AppDelegate *app = [UIApplication sharedApplication].delegate;
NSString *dateStr = [formatter stringFromDate:app.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:app.filepath]) {
[crashString writeToFile:app.filepath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}else{
NSFileHandle *outFile = [NSFileHandle fileHandleForWritingAtPath:app.filepath];
[outFile seekToEndOfFile];
[outFile writeData:[crashString dataUsingEncoding:NSUTF8StringEncoding]];
[outFile closeFile];
}
//把错误日志发送到邮箱
NSString *urlStr = [NSString stringWithFormat:@"mailto://邮箱账号?subject=bug报告&body=感谢您的配合!错误详情:%@",crashString ];
NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL:url];
}
使用

在AppDelegate的这个方法中编写如下代码

1
2
3
4
5
6
7
8
9
10
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
#if !(TARGET_IPHONE_SIMULATOR)//真机
//连接xcode时可以从监视器中看日志 没连接时Log日志会输出到文件中,
[self redirectNSLogToDocumentFolder];
NSLog(@"真机");
#else//模拟器
NSLog(@"模拟器");
#endif
return YES;
}