AFNetworkActivityLogger打印請求日志

Gitdi地址:https://github.com/peilinghui/AFNetworkActivityLogger
用法:

    [[AFNetworkActivityLogger sharedLogger] setLevel:AFLoggerLevelDebug];
//開啟日志
    [[AFNetworkActivityLogger sharedLogger] startLogging];

看了一下,也不難就一個.h一個.m。

  1. 在.h中
    用枚舉定義了Off,Debug,Info,Warn,還有Error.
    一個類方法sharedLogger.兩個實例方法startLogging和stopLogging;
  2. 在.m中
    先導入#import <AFNetworking/AFURLSessionManager.h>,主要是檢測網絡請求。
    先定義static變量NSURLRequest,NSError,NSURLResponse(Foundation框架中的)
    在實現中,類方法就是
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        _sharedLogger = [[self alloc] init];
    });```
在實例方法中就是
  
-startLogging中addObserve兩個@selector,一個是networkReqeustDidStart,一個是networkRequestDidFinish。
-stopLogging中removeObserve。
3. 實現兩個@selector
  a.networkReqeustDidStart
用到了runtime中的設置屬性 objc_setAssociatedObject,主要是是可以在switch中的Debug模式下加入代碼來實現。比如:

case TDFLoggerLevelDebug: {
NSMutableString *commandLineString = [@"http --form " mutableCopy];
[commandLineString appendFormat:@"%@ '%@' ", request.HTTPMethod, [[request URL] absoluteString]];

        [request.allHTTPHeaderFields enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSString * _Nonnull obj, BOOL * _Nonnull stop) {
            [commandLineString appendFormat:@"'%@':'%@' ", key, obj];
        }];
        
        if (body.length) {
            NSArray *parts = [body componentsSeparatedByString:@"&"];
            
            [parts enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSArray *pair = [obj componentsSeparatedByString:@"="];
                NSString *key = nil;
                
                if ([pair.firstObject respondsToSelector:@selector(stringByRemovingPercentEncoding)]) {
                    key = [pair.firstObject stringByRemovingPercentEncoding];
                }else {
                    key = [pair.firstObject stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                }
                
                NSString *value = nil;
                
                if ([pair.lastObject respondsToSelector:@selector(stringByRemovingPercentEncoding)]) {
                    value = [pair.lastObject stringByRemovingPercentEncoding];
                }else {
                    value = [pair.lastObject stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                }
                
                value = [value stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];
                
                [commandLineString appendFormat:@"'%@'=$'%@' ", key, value];
            }];
            
        }
        
        NSLog(@"%@", commandLineString);
    }
        
        break;
就可以在程序運行的時候調用服務器提供的接口,打印出信息:比如:
`http --form POST http://10.1.5.109:8080/boss-api//bill/v1/get_payment_record_by_day format='json' find_date='2016-07-21' pay_type='1' session_key='100008999262778ea3c4ffd4efed2e80c68fa2f9a7da33' page='1' sign='b233d533da2379d2fa0bd91c852922e8' page_size='20'`



b.networkRequestDidFinish
用官方的就行,還有在添加:`id responseObject = notification.userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey];`




4.寫個單元測試測試一下
  • (void)testLogger {
    XCTestExpectation *expectcation = [self expectationWithDescription:@"log test"];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:@"http://httpbin.org/post" parameters:@{
    @"key1" : @"va=lue1",
    @"key2" : @"{"key" : value}",
    @"key3" : @"valu''''''''''e3",
    @"key4" : @"value4",
    }progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
    [expectcation fulfill];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    [expectcation fulfill];
    }];

    [self waitForExpectationsWithTimeout:15.0f handler:^(NSError * _Nullable error) {

    }];
    }


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容