澳门威利斯人_威利斯人娱乐「手机版」

来自 网络资讯 2020-05-08 17:15 的文章
当前位置: 澳门威利斯人 > 网络资讯 > 正文

日志分析,iOS日志获取和实时浏览器显示日志

[self redirectSTD:STDERR_FILENO];

FILE * myFile = freopen([loggingPath cStringUsingEncoding:NSASCIIStringEncoding],"a ", stderrState of Qatar;//那句话已经重定向了,今后NSLog都输出到文件中去了,//……………….//复苏原本的dup2(originH1, STDE奥迪Q5昂Cora_FILENOState of Qatar;//就能够了

不开展日志重定向

iOS模拟器的日记其实是出口到系统中某些文件中了,好疑似定期压缩四个保存起来,我们只要找到十二分文件就足以tailf了。

图片 1

system.log文件在哪个地方.png

据他们说近期模拟器的identifier(windows-devices菜单State of Qatar按图示找到当前模拟器腺癌的system.log文件,右键finder呈现,然后直接tailf就足以啦。

 2016-06-15 12:57:17.286 TestNSlog[68073:1441419] ViewController viewDidLoadViewController viewDidLoad222

freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a ", stderr);

看看别人怎么玩日志的

  • https://my.oschina.net/bairrfhoinn/blog/201831
  • https://github.com/yechunjun/CCLogSystem
  • https://github.com/CocoaLumberjack/CocoaLumberjack
  • CocoaLumberjack教程
  • https://yohunl.com/iosri-zhi-huo-qu-he-shi-shi-liu-lan-qi-xian-shi-ri-zhi/
  • https://github.com/yourtion/SuperLogger
  • 实时浏览日志

大家的NSLog输出的是到 STDEHighlander冠道_FILENO 上,大家得以选择c语言的出口到文件的fprintf来证诺优能下

//log写入

Basic Libraries Related(理清那多少个库的涉嫌)

  • _
    • CocoaLumberjack
  • _
    • XLFacility
    • GCDNetworking
      • GCDNetworking is a networking framework based on GCD available under a friendly New BSD License.
    • GCDWebServer
      • GCDWebServer is a modern and lightweight GCD based HTTP 1.1 server designed to be embedded in OS X & iOS apps.
    • GCDTelnetServer
      • GCDTelnetServer is a drop-in embedded Telnet server for iOS and OS X apps.
  • _
    • CocoaAsyncSocket
      • CocoaAsyncSocket provides easy-to-use and powerful asynchronous socket libraries for Mac and iOS. The classes are described below.
      • GCDAsyncSocket is a TCP/IP socket networking library built atop Grand Central Dispatch.
      • GCDAsyncUdpSocket is a UDP/IP socket networking library built atop Grand Central Dispatch.
      • 日记达成用了CocoaLumberjack
    • CocoaHTTPServer(FMock工具用的那些
      • CocoaHTTPServer is a small, lightweight, embeddable HTTP server for Mac OS X or iOS applications.
      • 底层完毕用了CocoaAsyncSocket
    • RoutingHTTPServer
      • A routing API for CocoaHTTPServer
      • 底层完结用了CocoaHTTPServer

地点的章程,当测试,或然平日我们从未连接XCode时,想查看日志音讯,仍旧不太有利,试想,如若大家在须要的时候,能够间接用浏览器查看输出的log消息那该多好?

NSLog(@"logFilePath---> %@",logFilePath);

iOS日志重定向到文件

{
    //to log to document directory
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSString *loggingPath = [documentsPath stringByAppendingPathComponent:@"/mylog.log"];
    NSLog(@"%@", loggingPath);
    //redirect NSLog
    freopen([loggingPath cStringUsingEncoding:NSASCIIStringEncoding], "a ", stderr);
}

诸如此比我们就足以在计算机上面直接tail -f那几个文件,合营grep等一声令下进行日志深入分析了。

如上的格局,都以重定向文件,一旦重定向后,那么NSLog就不会再写到系统的syslog中去了,也就表示不能动用ASL接口获取到重定向后的多寡了.

NSString *logFilePath = [documentpath stringByAppendingPathComponent:fileName];

发源iOS App开辟时,调整台日志混乱,不便于深入分析的必要,爆发了这篇文章。

//在ios上可用的方式,还是得借助dup和dup2int originH1 = dup(STDERR_FILENO);FILE * myFile = freopen([loggingPath cStringUsingEncoding:NSASCIIStringEncoding], "a ", stderr);//这句话已经重定向了,现在NSLog都输出到文件中去了,//……………….//恢复原来的dup2(originH1, STDERR_FILENO);//就可以了

FILE * freopen (constchar* filename,constchar* mode, FILE * stream );

Basic Loggers Related(主要是Logger分类)

  • Apple System Logger
  • Standard output
  • standard error
  • File Logger
  • HTTP Server Logger
  • Telnet Server Logger
    • Telnet公约是TCP/IP左券族中的一员,是Internet远程登录服务的规范合同和第一措施。它为客户提供了在该地Computer上成功远程主机专业的本领。在终端使用者的微型机上行使telnet程序,用它连接到服务器。终端使用者可以在telnet程序中输入指令,这个命令会在服务器上运维,就如直接在服务器的调节台上输入同样。
  • TCP Server Logger
  • UDP Server Logger
  • TCP Client Logger
  • UDP Client Logger
  • Onscreen Logging Overlay
  • Custom Loggers
  • Custom Logger fomatters

ASL的益处是没有重定向文件,所以不会耳闻则诵Xcode等调节台的出口,它是一种非侵入式的读取的诀要,相仿于大家读取数据库的公文,大家只是读取数据,并不曾将本来的数据库文件删除.

相近大家都会在使用中放置三个开关,开启大概关闭Log日志的重定向,在上头,大家运用标准C的freopen将stderr重定向到大家的文本中了,那么难点来了,怎么重定向回去啊???

怎么更有益于啊?

To give yourself faster access to logs via terminal, you can add an alias to your .bash_profile file by typing:
echo "alias simulatorlog='tail -f ~/Library/Logs/iOS Simulator/7.0/system.log'" >> ~/.bash_profile
After it you can simply type simulatorlog into terminal window to access the logs.
像本人要好的微管理机,是这么配的(查看One plus6的日记State of Qatar:
alias mylog6='tail -f /Users/test/Library/Logs/CoreSimulator/0A5E599A-D202-4502-8E3C-B6E97840E7ED/system.log'
翻看日志时,直接mylog6 | grep something
Enjoy.

============================分割线===============================

不重定向NSLog,怎么读取全体的log呢?

//完成上面包车型客车方式成功NSLog重定向到文件

Guide(演示内容)

  1. XLFacility --> HTTPServer
    • http://127.0.0.1:8080
  2. XLFacility --> TelnetServer
    • telnet localhost 2323
  3. XLFacility --> Onscreen Logging Overlay
  4. CocoaLumberjack --> UDPClient
    • start udp server
    • test udp client logger
    • 下边是四个总结的udp server代码:
#!/usr/bin/env python
# UDP Echo Server -  udpserver.py
# code by www.cppblog.com/jerryma
import socket, traceback

host = '127.0.0.1'
port = 8888

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))

while 1:
    try:
        message, address = s.recvfrom(8192)
        print "Got data from", address, ": ", message
        s.sendto(message, address)
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        traceback.print_exc()

在应用程序的Info.plist文件中加多UIFileSharingEnabled键,并将键值设置为YES。将您愿意大利共产党享的文件放在应用程序的Documents目录。一旦道具插入到客商计算机,iTunes 9.1就能在当选设备的Apps标签中展现叁个File Sharing区域。今后,用户就足以向该目录添Gavin件或然将文件移动到桌面Computer中

恢复生机重定向摘录:https://yohunl.com/iosri-zhi-huo-qu-he-shi-shi-liu-lan-qi-xian-shi-ri-zhi/

基础票

#define kMinRefreshDelay 500 // In milliseconds@interface HttpServerLogger ()@property (nonatomic,strong) GCDWebServer* webServer;@end@implementation HttpServerLogger  (instancetype)shared { static dispatch_once_t onceToken; static HttpServerLogger *shared; dispatch_once(&onceToken, ^{ shared = [HttpServerLogger new]; }); return shared;}- (GCDWebServer *)webServer { if (!_webServer) { _webServer = [[GCDWebServer alloc] init]; __weak __typeof__ weakSelf = self; // Add a handler to respond to GET requests on any URL [_webServer addDefaultHandlerForMethod:@"GET" requestClass:[GCDWebServerRequest class] processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) { return [weakSelf createResponseBody:request]; }]; NSLog(@"Visit %@ in your web browser", _webServer.serverURL); } return _webServer;}- startServer{ // Use convenience method that runs server on port 8080 // until SIGINT (Ctrl-C in Terminal) or SIGTERM is received [self.webServer startWithPort:8080 bonjourName:nil]; }- stopServer { [_webServer stop]; _webServer = nil;}//当浏览器请求的时候,返回一个由日志信息组装成的html返回给浏览器- (GCDWebServerDataResponse *)createResponseBody :(GCDWebServerRequest* )request{ GCDWebServerDataResponse *response = nil; NSString* path = request.path; NSDictionary* query = request.query; //NSLog(@"path = %@,query = %@",path,query); NSMutableString* string; if ([path isEqualToString:@"/"]) { string = [[NSMutableString alloc] init]; [string appendString:@"<!DOCTYPE html><html lang="en">"]; [string appendString:@"<head><meta charset="utf-8"></head>"]; [string appendFormat:@"<title>%s[%i]</title>", getprogname(), getpid()]; [string appendString:@"<style> body {n margin: 0px;n font-family: Courier, monospace;n font-size: 0.8em;n }n table {n width: 100%;n border-collapse: collapse;n }n tr {n vertical-align: top;n }n tr:nth-child {n background-color: #eeeeee;n }n td {n padding: 2px 10px;n }n #footer {n text-align: center;n margin: 20px 0px;n color: darkgray;n }n .error {n color: red;n font-weight: bold;n }n </style>"]; [string appendFormat:@"<script type="text/javascript">n var refreshDelay = %i;n var footerElement = null;n function updateTimestamp() {n var now = new Date();n footerElement.innerHTML = "Last updated on "   now.toLocaleDateString()   " "   now.toLocaleTimeString();n }n function refresh() {n var timeElement = document.getElementById("maxTime");n var maxTime = timeElement.getAttribute("data-value");n timeElement.parentNode.removeChild(timeElement);n n var xmlhttp = new XMLHttpRequest();n xmlhttp.onreadystatechange = function() {n if (xmlhttp.readyState == 4) {n if (xmlhttp.status == 200) {n var contentElement = document.getElementById("content");n contentElement.innerHTML = contentElement.innerHTML   xmlhttp.responseText;n updateTimestamp();n setTimeout(refresh, refreshDelay);n } else {n footerElement.innerHTML = "Connection failed! Reload page to try again.";n }n }n }n xmlhttp.open("GET", "/log?after="   maxTime, true);n xmlhttp.send();n }n window.onload = function() {n footerElement = document.getElementById("footer");n updateTimestamp();n setTimeout(refresh, refreshDelay);n }n </script>", kMinRefreshDelay]; [string appendString:@"</head>"]; [string appendString:@"<body>"]; [string appendString:@"<table><tbody id="content">"]; [self _appendLogRecordsToString:string afterAbsoluteTime:0.0]; [string appendString:@"</tbody></table>"]; [string appendString:@"<div id="footer"></div>"]; [string appendString:@"</body>"]; [string appendString:@"</html>"]; } else if ([path isEqualToString:@"/log"] && query[@"after"]) { string = [[NSMutableString alloc] init]; double time = [query[@"after"] doubleValue]; [self _appendLogRecordsToString:string afterAbsoluteTime:time]; } else { string = [@" <html><body><p>无数据</p></body></html>" mutableCopy]; } if (string == nil) { string = [@"" mutableCopy]; } response = [GCDWebServerDataResponse responseWithHTML:string]; return response;}- _appendLogRecordsToString:(NSMutableString*)string afterAbsoluteTime:time { __block double maxTime = time; NSArray<SystemLogMessage *> *allMsg = [SystemLogManager allLogAfterTime:time]; [allMsg enumerateObjectsUsingBlock:^(SystemLogMessage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { const char* style = "color: dimgray;"; NSString* formattedMessage = [self displayedTextForLogMessage:obj]; [string appendFormat:@"<tr style="%s">%@</tr>", style, formattedMessage]; if (obj.timeInterval > maxTime) { maxTime = obj.timeInterval ; } }]; [string appendFormat:@"<tr id="maxTime" data-value="%f"></tr>", maxTime]; }- (NSString *)displayedTextForLogMessage:(SystemLogMessage *)msg{ NSMutableString *string = [[NSMutableString alloc] init]; [string appendFormat:@"<td>%@</td> <td>%@</td> <td>%@</td>",[SystemLogMessage logTimeStringFromDate:msg.date ],msg.sender, msg.messageText]; return string; }@end

[fileManager removeItemAtPath:logFilePath error:nil];

说说NSLog

  • 调用NSLogv => Logs an error message to the Apple System Log facility.
  • Output from NSLogv is serialized, in that only one thread in a process can be doing the writing/logging described above at a time.
    • STDERR_FILENO
    • ASL

对此httpservergithub上相比显赫的有CocoaHTTPServer,这几个曾经四年没更新了,不引入应用GCDWebServer 小编一向在保卫安全,传闻品质也不利,推荐使用那个,上边包车型客车demo也应用的那个

//在ios上可用的措施,仍旧得依赖dup和dup2intoriginH1 = dup(STDE大切诺基景逸SUV_FILENO);

分享篇

上面是组内分享时用的md文件,是贰个大约的计算性的东西,就算并没有详细的打开(分享时口说呗,写起来好累赘的指南),但以为对于理思路还是蛮好的。

选用的时候,开启webserver服务,在同多少个局域网下, 使用

- (void)redirectNSLogToDucumentFile{

身为,一旦器械连接上电脑,能够经过iTune查看钦赐应用程序的分享文件夹,将文件拷贝到你的Computer上看

要想重定向回去,那么大家要求通晓stderr原本的文件路径,很缺憾,这一个在分化平新竹是不平等的,在iOS平台,由于沙盒机制,我们也并无法一贯运用沙盒外的公文 对此,freopen将无法,要重定向回去,只好利用Unix的主意dup和dup2!

_sourt_t = [self _startCapturingWritingToFD:STDERR_FILENO];

}

ASL读取log的基本代码

NSFileManager *fileManager = [NSFileManager defaultManager];

使用c语言的freopen函数,实行重定向,将写往stderr的剧情重定向到大家制定的文本中去,一旦试行了上述代码,那么在此个现在的NSLog将不会在调整台展现了,会间接出口在文书mylog.log中!在模拟器中,大家得以接收终端的tail命令(tail -f mylog.log卡塔尔(قطر‎对那么些文件实行实时查看,就仿佛大家在xcode的出口窗口中看见的那样,你还是能够构成grep命令进行实时过滤查看,极其常有帮忙在大批量的日志音信中相当慢定位到大家要的日记新闻

//删除已经存在文件

图片 2演示2.gif

NSString *documentpath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

诚如大家都会在接纳中放置三个按键,开启大概关闭Log日志的重定向,在上头,大家应用规范C的freopen将stderr重定向到大家的文书中了,那么难题来了,怎么重定向回去吧???

NSString *fileName = [NSString stringWithFormat:@"%@.log",[NSDate date]];

本文由澳门威利斯人发布于网络资讯,转载请注明出处:日志分析,iOS日志获取和实时浏览器显示日志

关键词: 澳门威利斯人 日记本 IOS 实时 日志