fishhook实现NSLog日志获取
2019-07-30 本文已影响0人
格雷s
在项目开发中,我们经常会通过log去打印日志记录,然而线上的app我们无法直接获取log日志,这里分享下怎样去重定向我们的NSLog方法
1.Hook NSLog方法
NSLog本身是一个C函数,我们通过 fishhook来截取
2.dup2重定向
#import "fishhook.h"
#if !DEBUG
//函数指针,用来保存原始的函数的地址
static void (*origin_nslog)(NSString *format,...);
void redirect_nslog(NSString *format,...) {
//在这里执行自己的日志处理逻辑
printf("测试");
//继续执行原log
va_list va;
va_start(va, format);
NSLogv(format,va);
va_end(va);
}
#endif
int main(int argc, char * argv[]) {
@autoreleasepool {
#if !DEBUG
//method1:利用fishhook,截取NSLog方法的实现
// struct rebinding nslog_rebinding = {"NSLog",redirect_nslog,(void*)&origin_nslog};
// struct rebinding rebs[] = {nslog_rebinding};
// rebind_symbols(rebs, 1);
//method2:
//NSLog最后在输出的时候会用STDERR句柄进行错误系统日志的统计,
//O_RDWR,可读可写打开 O_CREAT,若此文件不存在,则创建
//dup2重定向之后,就不能在控制台看到日志了,一般在线上做日志统计,并上传
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
path = [path stringByAppendingString:@"/log.txt"];
//path是log最终输出路径
int fd = open(path.UTF8String, (O_RDWR|O_CREAT),0644);
dup2(fd, STDERR_FILENO);
#endif
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}