Permalink
Browse files

Initial Commit

  • Loading branch information...
mattt committed Aug 21, 2013
0 parents commit b3aa9cc784ab5ed9f0d4409e0dfedc3a1b3678e6
Showing with 346 additions and 0 deletions.
  1. +109 −0 AFNetworkActivityLogger.h
  2. +167 −0 AFNetworkActivityLogger.m
  3. +13 −0 AFNetworkActivityLogger.podspec
  4. +19 −0 LICENSE
  5. +38 −0 README.md
@@ -0,0 +1,109 @@
// AFNetworkActivityLogger.h
//
// Copyright (c) 2011 AFNetworking (http://afnetworking.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSUInteger, AFHTTPRequestLoggerLevel) {
AFLoggerLevelOff,
AFLoggerLevelDebug,
AFLoggerLevelInfo,
AFLoggerLevelWarn,
AFLoggerLevelError,
AFLoggerLevelFatal = AFLoggerLevelOff,
};
/**
`AFNetworkActivityLogger` logs requests and responses made by AFNetworking, with an adjustable level of detail.
Applications should enable the shared instance of `AFNetworkActivityLogger` in `AppDelegate -application:didFinishLaunchingWithOptions:`:
[[AFNetworkActivityLogger sharedLogger] startLogging];
`AFNetworkActivityLogger` listens for `AFNetworkingOperationDidStartNotification` and `AFNetworkingOperationDidFinishNotification` notifications, which are posted by AFNetworking as request operations are started and finish. For further customization of logging output, users are encouraged to implement desired functionality by listening for these notifications.
*/
@interface AFNetworkActivityLogger : NSObject
/**
The level of logging detail. See "Logging Levels" for possible values. `AFLoggerLevelInfo` by default.
*/
@property (nonatomic, assign) AFHTTPRequestLoggerLevel level;
/**
Only log requests conforming to the specified predicate, if specified. `nil` by default.
@discussion Each notification has an associated `NSURLRequest`. To filter out request and response logging, such as all network activity made to a particular domain, this predicate can be set to match against the appropriate URL string pattern.
*/
@property (nonatomic, strong) NSPredicate *filterPredicate;
/**
Returns the shared logger instance.
*/
+ (instancetype)sharedLogger;
/**
Start logging requests and responses.
*/
- (void)startLogging;
/**
Stop logging requests and responses.
*/
- (void)stopLogging;
@end
///----------------
/// @name Constants
///----------------
/**
## Logging Levels
The following constants specify the available logging levels for `AFNetworkActivityLogger`:
enum {
AFLoggerLevelOff,
AFLoggerLevelDebug,
AFLoggerLevelInfo,
AFLoggerLevelWarn,
AFLoggerLevelError,
AFLoggerLevelFatal = AFLoggerLevelOff,
}
`AFLoggerLevelOff`
Do not log requests or responses.
`AFLoggerLevelDebug`
Logs HTTP method, URL, header fields, & request body for requests, and status code, URL, header fields, response string, & elapsed time for responses.
`AFLoggerLevelInfo`
Logs HTTP method & URL for requests, and status code, URL, & elapsed time for responses.
`AFLoggerLevelWarn`
Logs HTTP method & URL for requests, and status code, URL, & elapsed time for responses, but only for failed requests.
`AFLoggerLevelError`
Equivalent to `AFLoggerLevelWarn`
`AFLoggerLevelFatal`
Equivalent to `AFLoggerLevelOff`
*/
@@ -0,0 +1,167 @@
// AFNetworkActivityLogger.h
//
// Copyright (c) 2011 AFNetworking (http://afnetworking.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "AFNetworkActivityLogger.h"
#import "AFURLConnectionOperation.h"
#import "AFURLSessionManager.h"
#import <objc/runtime.h>
static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) {
NSURLRequest *request = nil;
if ([[notification object] isKindOfClass:[AFURLConnectionOperation class]]) {
request = [(AFURLConnectionOperation *)[notification object] request];
} else if ([[notification object] isKindOfClass:[NSURLSessionTask class]]) {
request = [(NSURLSessionTask *)[notification object] originalRequest];
}
return request;
}
@implementation AFNetworkActivityLogger
+ (instancetype)sharedLogger {
static AFNetworkActivityLogger *_sharedLogger = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedLogger = [[self alloc] init];
});
return _sharedLogger;
}
- (id)init {
self = [super init];
if (!self) {
return nil;
}
self.level = AFLoggerLevelInfo;
return self;
}
- (void)dealloc {
[self stopLogging];
}
- (void)startLogging {
[self stopLogging];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingOperationDidStartNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingOperationDidFinishNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidStartNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidFinishNotification object:nil];
}
- (void)stopLogging {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - NSNotification
static void * AFNetworkRequestStartDate = &AFNetworkRequestStartDate;
- (void)networkRequestDidStart:(NSNotification *)notification {
NSURLRequest *request = AFNetworkRequestFromNotification(notification);
if (!request) {
return;
}
if (request && self.filterPredicate && [self.filterPredicate evaluateWithObject:request]) {
return;
}
objc_setAssociatedObject(notification.object, AFNetworkRequestStartDate, [NSDate date], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
NSString *body = nil;
if ([request HTTPBody]) {
body = [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding];
}
switch (self.level) {
case AFLoggerLevelDebug:
NSLog(@"%@ '%@': %@ %@", [request HTTPMethod], [[request URL] absoluteString], [request allHTTPHeaderFields], body);
break;
case AFLoggerLevelInfo:
NSLog(@"%@ '%@'", [request HTTPMethod], [[request URL] absoluteString]);
break;
default:
break;
}
}
- (void)networkRequestDidFinish:(NSNotification *)notification {
NSURLRequest *request = AFNetworkRequestFromNotification(notification);
NSURLResponse *response = [notification.object response];
NSError *error = [notification.object error];
if (!request && !response) {
return;
}
if (request && self.filterPredicate && [self.filterPredicate evaluateWithObject:request]) {
return;
}
NSUInteger responseStatusCode = 0;
NSDictionary *responseHeaderFields = nil;
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
responseStatusCode = [(NSHTTPURLResponse *)response statusCode];
responseHeaderFields = [(NSHTTPURLResponse *)response allHeaderFields];
}
NSString *responseString = nil;
if ([[notification object] respondsToSelector:@selector(responseString)]) {
responseString = [[notification object] responseString];
}
NSTimeInterval elapsedTime = [[NSDate date] timeIntervalSinceDate:objc_getAssociatedObject(notification.object, AFNetworkRequestStartDate)];
if (error) {
switch (self.level) {
case AFLoggerLevelDebug:
case AFLoggerLevelInfo:
case AFLoggerLevelWarn:
case AFLoggerLevelError:
NSLog(@"[Error] %@ '%@' (%ld) [%.04f s]: %@", [request HTTPMethod], [[response URL] absoluteString], (long)responseStatusCode, elapsedTime, error);
default:
break;
}
} else {
switch (self.level) {
case AFLoggerLevelDebug:
NSLog(@"%ld '%@' [%.04f s]: %@ %@", (long)responseStatusCode, [[response URL] absoluteString], elapsedTime, responseHeaderFields, responseString);
break;
case AFLoggerLevelInfo:
NSLog(@"%ld '%@' [%.04f s]", (long)responseStatusCode, [[response URL] absoluteString], elapsedTime);
break;
default:
break;
}
}
}
@end
@@ -0,0 +1,13 @@
Pod::Spec.new do |s|
s.name = 'AFNetworkActivityLogger'
s.version = '2.0.0'
s.license = 'MIT'
s.summary = 'AFNetworking 2.0 Extension for Network Request Logging'
s.homepage = 'https://github.com/AFNetworking/AFNetworkActivityLogger'
s.authors = { 'Mattt Thompson' => 'm@mattt.me' }
s.source = { :git => 'https://github.com/AFNetworking/AFNetworkActivityLogger.git', :tag => '2.0.0' }
s.source_files = 'AFNetworkActivityLogger.{h,m}'
s.requires_arc = true
s.dependency 'AFNetworking', '~> 2.0'
end
19 LICENSE
@@ -0,0 +1,19 @@
Copyright (c) 2013 AFNetworking (http://afnetworking.com/)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,38 @@
# AFNetworkActivityLogger
`AFNetworkActivityLogger` is an extension for [AFNetworking](http://github.com/AFNetworking/AFNetworking/) 2.0 that logs network requests as they are sent and received.
> `AFNetworkActivityLogger` listens for `AFNetworkingOperationDidStartNotification` / `AFNetworkingOperationDidFinishNotification` and `AFNetworkingTaskDidStartNotification` / `AFNetworkingTaskDidFinishNotification` notifications, which are posted by AFNetworking as request operations and session tasks are started and finish. For further customization of logging output, users are encouraged to implement desired functionality by listening for these notifications.
## Usage
Add the following code to `AppDelegate.m -application:didFinishLaunchingWithOptions:`:
``` objective-c
[[AFNetworkActivityLogger sharedLogger] startLogging];
```
Now all `AFURLConnectionOperation` and `NSURLSessionTask` objects created by an `AFURLSessionManager` will have their request and response logged to the console, a la:
```
GET http://example.com/foo/bar.json
200 http://example.com/foo/bar.json
```
If the default logging level is too verbose—say, if you only want to know when requests fail—then changing it is as simple as:
``` objective-c
[[AFNetworkActivityLogger sharedLogger] setLevel:AFLoggerLevelError];
```
## Contact
Mattt Thompson
- http://github.com/mattt
- http://twitter.com/mattt
- m@mattt.me
## License
AFNetworkActivityLogger is available under the MIT license. See the LICENSE file for more info.

0 comments on commit b3aa9cc

Please sign in to comment.