2010년 4월 23일 금요일

iphone logger

0. 목적
simply iphone logger

1. 참고
http://stackoverflow.com/questions/202299/logging-to-a-file-on-the-iphone
http://www.iphonedevsdk.com/forum/iphone-sdk-development/8162-debugging-tip-nslog.html

2. 조건
configuration=debug 일때만 로그를 남긴다.

3. 구현

3-1. macro setting
preprocessor macro 에 설정




3-2. Logger.h , m

#ifdef DEBUG

#define Log(s, ...) NSLog(s, ##__VA_ARGS__)

#else

#define Log(s, ...)

#endif


@interface Logger : NSObject {


}

+ (NSString*)path;

+ (void)write:(NSString*)str;

+ (NSString*)read;

+ (void)remove;


@end


#import "Logger.h"


@implementation Logger


+ (NSString*)path{

NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *path = [docsDirectory stringByAppendingPathComponent:@"log.txt"];

return path;

}


+ (void)write:(NSString*)str{

#ifdef DEBUG

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"HH.mm.ss"];

NSString* log = [NSString stringWithFormat:@"%@-%@\n\r" , [dateFormatter stringFromDate:[NSDate date]] , str];

[dateFormatter release];

NSString* storeLog = [Logger read] ? [Logger read] : @"";

NSData *dataToWrite = [[NSString stringWithString:[storeLog stringByAppendingString:log]] dataUsingEncoding:NSUTF8StringEncoding];

[dataToWrite writeToFile:[Logger path] atomically:YES];

#endif

}


+ (NSString*)read{

return [[[NSString alloc] initWithContentsOfFile:[Logger path]] autorelease];  

}


+ (void)remove{

NSFileManager *fileManager = [NSFileManager defaultManager];

if ([fileManager fileExistsAtPath:[Logger path]]){

[fileManager removeItemAtPath:[Logger path] error:NULL];

}

[fileManager release];

}


@end


3-3 delegate 에 추가

#ifdef DEBUG

#if TARGET_IPHONE_SIMULATOR == 0

Log([Logger read]);

[Logger remove];

#endif

#endif




댓글 없음:

댓글 쓰기