iOS中日志同步獲取NSLog重定向以及其他詳解

前言

創(chuàng)新互聯(lián)主營靈石網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,重慶APP開發(fā),靈石h5微信小程序搭建,靈石網(wǎng)站營銷推廣歡迎靈石等地區(qū)企業(yè)咨詢

對于那些做后端開發(fā)的工程師來說,看LOG解Bug應(yīng)該是理所當(dāng)然的事,但我接觸到的移動應(yīng)用開發(fā)的工程師里面,很多人并沒有這個(gè)意識,查Bug時(shí)總是一遍一遍的試圖重現(xiàn),試圖調(diào)試,特別是對一些不太容易重現(xiàn)的Bug經(jīng)常焦頭爛額。

我們在真機(jī)測試時(shí)經(jīng)常會發(fā)現(xiàn)一個(gè)難題是無法查看真機(jī)的NSLog類型的實(shí)時(shí)日志,這時(shí)候需要RD復(fù)現(xiàn)問題來定位當(dāng)時(shí)的日志,以方便查找問題。這個(gè)問題在測試中是非常常見的,也是功能測試會花費(fèi)比較長時(shí)間的一個(gè)原因。

以下我們討論下能即時(shí)查看日志的幾種方案。

NSLog輸出到哪里?

在iOS開發(fā)中,我們經(jīng)常會用到NSLog調(diào)試,但是我們卻不太了解它。在NSLog本質(zhì)是一個(gè)C函數(shù),它的函數(shù)聲明如下:
FOUNDATION_EXPORT void NSLog(NSString *format, ...)

系統(tǒng)對它的說明是:Logs an error message to the Apple System Log facility.。他是用來輸出信息到標(biāo)準(zhǔn)Error控制臺上去的,其內(nèi)部其實(shí)是使用Apple System Log的API。在調(diào)試階段,日志會輸出到到Xcode中,而在iOS真機(jī)上,它會輸出到系統(tǒng)的/var/log/syslog這個(gè)文件中。

在iOS中,把日志輸出到文件中的句柄在unistd.h文件中有定義:

#define STDIN_FILENO 0 /* standard input file descriptor */
#define STDOUT_FILENO 1 /* standard output file descriptor */
#define STDERR_FILENO 2 /* standard error file descriptor */

NSLog輸出的是到STDERR_FILENO上,我們可以在iOS中使用c語言輸出到的文件的fprintf來驗(yàn)證:

NSLog(@"iOS NSLog");
fprintf (stderr, "%s\n", "fprintf log");

由于fprintf并不會像NSLog那樣,在內(nèi)部調(diào)用ASL接口,所以只是單純的輸出信息,并沒有添加日期、進(jìn)程名、進(jìn)程id等,也不會自動換行。

ASL讀取日志

首先我們可以想到的是既然日志寫入系統(tǒng)的syslog中,那我們可以直接讀取這些日志。從ASL讀取日志的核心代碼如下:

#import <asl.h>
// 從日志的對象aslmsg中獲取我們需要的數(shù)據(jù)
+(instancetype)logMessageFromASLMessage:(aslmsg)aslMessage{
 SystemLogMessage *logMessage = [[SystemLogMessage alloc] init];
 const char *timestamp = asl_get(aslMessage, ASL_KEY_TIME);
 if (timestamp) {
  NSTimeInterval timeInterval = [@(timestamp) integerValue];
  const char *nanoseconds = asl_get(aslMessage, ASL_KEY_TIME_NSEC);
  if (nanoseconds) {
   timeInterval += [@(nanoseconds) doubleValue] / NSEC_PER_SEC;
  }
  logMessage.timeInterval = timeInterval;
  logMessage.date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
 }
 const char *sender = asl_get(aslMessage, ASL_KEY_SENDER);
 if (sender) {
  logMessage.sender = @(sender);
 }
 const char *messageText = asl_get(aslMessage, ASL_KEY_MSG);
 if (messageText) {
  logMessage.messageText = @(messageText);//NSLog寫入的文本內(nèi)容
 }
 const char *messageID = asl_get(aslMessage, ASL_KEY_MSG_ID);
 if (messageID) {
  logMessage.messageID = [@(messageID) longLongValue];
 }
 return logMessage;
}
+ (NSMutableArray<SystemLogMessage *> *)allLogMessagesForCurrentProcess{
 asl_object_t query = asl_new(ASL_TYPE_QUERY);
 // Filter for messages from the current process. Note that this appears to happen by default on device, but is required in the simulator.
 NSString *pidString = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]];
 asl_set_query(query, ASL_KEY_PID, [pidString UTF8String], ASL_QUERY_OP_EQUAL);
 aslresponse response = asl_search(NULL, query);
 aslmsg aslMessage = NULL;
 NSMutableArray *logMessages = [NSMutableArray array];
 while ((aslMessage = asl_next(response))) {
  [logMessages addObject:[SystemLogMessage logMessageFromASLMessage:aslMessage]];
 }
 asl_release(response);
 return logMessages;
}

使用以上方法的好處是不會影響Xcode控制臺的輸出,可以用非侵入性的方式來讀取日志。

NSLog重定向

另一種方式就是重定向NSLog,這樣NSLog就不會寫到系統(tǒng)的syslog中了。

dup2重定向

通過重定向,可以直接截取stdout,stderr等標(biāo)準(zhǔn)輸出的信息,然后保存在想要存儲的位置,上傳到服務(wù)器或者顯示到View上。

要做到重定向,需要通過NSPipe創(chuàng)建一個(gè)管道,pipe有讀端和寫端,然后通過dup2將標(biāo)準(zhǔn)輸入重定向到pipe的寫端。再通過NSFileHandle監(jiān)聽pipe的讀端,最后再處理讀出的信息。

之后通過printf或者NSLog寫數(shù)據(jù),都會寫到pipe的寫端,同時(shí)pipe會將這些數(shù)據(jù)直接傳送到讀端,最后通過NSFileHandle的監(jiān)控函數(shù)取出這些數(shù)據(jù)。

核心代碼如下:

- (void)redirectStandardOutput{
 //記錄標(biāo)準(zhǔn)輸出及錯(cuò)誤流原始文件描述符
 self.outFd = dup(STDOUT_FILENO);
 self.errFd = dup(STDERR_FILENO);
#if BETA_BUILD
 stdout->_flags = 10;
 NSPipe *outPipe = [NSPipe pipe];
 NSFileHandle *pipeOutHandle = [outPipe fileHandleForReading];
 dup2([[outPipe fileHandleForWriting] fileDescriptor], STDOUT_FILENO);
 [pipeOutHandle readInBackgroundAndNotify];
 stderr->_flags = 10;
 NSPipe *errPipe = [NSPipe pipe];
 NSFileHandle *pipeErrHandle = [errPipe fileHandleForReading];
 dup2([[errPipe fileHandleForWriting] fileDescriptor], STDERR_FILENO);
 [pipeErrHandle readInBackgroundAndNotify];
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(redirectOutNotificationHandle:) name:NSFileHandleReadCompletionNotification object:pipeOutHandle];
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(redirectErrNotificationHandle:) name:NSFileHandleReadCompletionNotification object:pipeErrHandle];
#endif
}
-(void)recoverStandardOutput{
#if BETA_BUILD
 dup2(self.outFd, STDOUT_FILENO);
 dup2(self.errFd, STDERR_FILENO);
 [[NSNotificationCenter defaultCenter] removeObserver:self];
#endif
}
// 重定向之后的NSLog輸出
- (void)redirectOutNotificationHandle:(NSNotification *)nf{
#if BETA_BUILD
 NSData *data = [[nf userInfo] objectForKey:NSFileHandleNotificationDataItem];
 NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
 // YOUR CODE HERE... 保存日志并上傳或展示
#endif
 [[nf object] readInBackgroundAndNotify];
}
// 重定向之后的錯(cuò)誤輸出
- (void)redirectErrNotificationHandle:(NSNotification *)nf{
#if BETA_BUILD
 NSData *data = [[nf userInfo] objectForKey:NSFileHandleNotificationDataItem];
 NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
 // YOUR CODE HERE... 保存日志并上傳或展示
#endif
 [[nf object] readInBackgroundAndNotify];
}

文件重定向

另一種重定向的方式是利用c語言的freopen函數(shù)進(jìn)行重定向,將寫往stderr的內(nèi)容重定向到我們制定的文件中去,一旦執(zhí)行了上述代碼那么在這個(gè)之后的NSLog將不會在控制臺顯示了,會直接輸出在指定的文件中。

在模擬器中,我們可以使用終端的tail命令(tail -f xxx.log)對這個(gè)文件進(jìn)行實(shí)時(shí)查看,就如同我們在Xcode的輸出窗口中看到的那樣,你還可以結(jié)合grep命令進(jìn)行實(shí)時(shí)過濾查看,非常方便在大量的日志信息中迅速定位到我們要的日志信息。

FILE * freopen ( const char * filename, const char * mode, FILE * stream );

具體代碼如下:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *loggingPath = [documentsPath stringByAppendingPathComponent:@"/xxx.log"];
//redirect NSLog
freopen([loggingPath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);

這樣我們就可以把可獲取的日志文件發(fā)送給服務(wù)端或者通過itunes共享出來。但是由于iOS嚴(yán)格的沙盒機(jī)制,我們無法知道stderr原來的文件路徑,也無法直接使用沙盒外的文件,所以freopen無法重定向回去,只能使用第1點(diǎn)所述的dup和dup2來實(shí)現(xiàn)。

// 重定向
int origin1 = dup(STDERR_FILENO);
FILE * myFile = freopen([loggingPath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
// 恢復(fù)重定向
dup2(origin1, STDERR_FILENO);

使用GCD的dispatch Source重定向方式

具體代碼如下:

- (dispatch_source_t)_startCapturingWritingToFD:(int)fd {
 int fildes[2];
 pipe(fildes); // [0] is read end of pipe while [1] is write end
 dup2(fildes[1], fd); // Duplicate write end of pipe "onto" fd (this closes fd)
 close(fildes[1]); // Close original write end of pipe
 fd = fildes[0]; // We can now monitor the read end of the pipe
 char* buffer = malloc(1024);
 NSMutableData* data = [[NSMutableData alloc] init];
 fcntl(fd, F_SETFL, O_NONBLOCK);
 dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, fd, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));
 dispatch_source_set_cancel_handler(source, ^{
  free(buffer);
 });
 dispatch_source_set_event_handler(source, ^{
  @autoreleasepool {
   while (1) {
    ssize_t size = read(fd, buffer, 1024);
    if (size <= 0) {
     break;
    }
    [data appendBytes:buffer length:size];
    if (size < 1024) {
     break;
    }
   }
   NSString *aString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
   //printf("aString = %s",[aString UTF8String]);
   //NSLog(@"aString = %@",aString);
   // Do something
  }
 });
 dispatch_resume(source);
 return source;
}

日志同步/上傳

重定向或者存儲的數(shù)據(jù)可以傳到服務(wù)端或者通過server同步到網(wǎng)頁上,就可以更方便的看到這些數(shù)據(jù)了。

如果想再網(wǎng)頁端實(shí)時(shí)查看日志,可以在App內(nèi)置一個(gè)小型http web服務(wù)器。GitHub上開源的項(xiàng)目有GCDWebServer,可以使用該工具,在APP開啟webserver服務(wù),并在同一局域網(wǎng)下,使用http://localhost:8080來請求最新日志了。

上傳服務(wù)端的部分很簡單,實(shí)現(xiàn)簡單的網(wǎng)絡(luò)請求就可以,這兒不做敘述。

另外在實(shí)際項(xiàng)目中,可以設(shè)置一個(gè)開關(guān)來開啟或關(guān)閉這個(gè)重定向,在調(diào)試測試的過程中可以打開開關(guān)來查看程序當(dāng)前的日志。

通過以上處理,真機(jī)測試中,日志就可以很方便的獲取和查看了,這樣能節(jié)省不少人力和時(shí)間成本。

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對創(chuàng)新互聯(lián)的支持。

參考文檔

  • iOS IO重定向
  • iOS 日志

網(wǎng)站欄目:iOS中日志同步獲取NSLog重定向以及其他詳解
文章來源:http://muchs.cn/article10/jioogo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動態(tài)網(wǎng)站、搜索引擎優(yōu)化、虛擬主機(jī)、移動網(wǎng)站建設(shè)、品牌網(wǎng)站建設(shè)、Google

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司