Create a debug log for objective c project

Tuesday, September 20, 2011

This is to create a simple log for debugging purposes in objective C

- (void)debugLog:(NSString*)message
{
    NSString *ReportPath = /Your path to generate the log/
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSString *fileLog = _ReportPath;
    fileLog = [fileLog stringByAppendingString:@"/myLog.log"];

    NSError *error;
    NSFileManager *fileManager = [[NSFileManager alloc] init];

    // if the path was deleted create it again
    BOOL isDir = NO;
    if (!([fileManager fileExistsAtPath:_ReportPath isDirectory:&isDir] && isDir))
    {
        if(![fileManager createDirectoryAtPath:_ReportPath withIntermediateDirectories:YES attributes:nil error:&error ])
            NSLog(@"DNMainController: Error on creating _ReportPath - %@", [error localizedDescription]);
    }

    //if file doesnt exist, create it first for later appending
    if(![fileManager fileExistsAtPath:fileLog isDirectory:NO])
    {
        if(![@"" writeToFile: fileLog atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
            NSLog(@"UtilClass: Error on creating _DebugLog file - %@",[error localizedFailureReason]);
            [fileManager release];
            [pool drain];
            return;
        }
    }
   
    NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:fileLog];
    if (handle) {
        [handle seekToEndOfFile];
        NSMutableData *data = [NSMutableData data];
        [data appendData:[message dataUsingEncoding:NSUTF8StringEncoding]];
        [handle writeData:data];
        [handle closeFile];       
    }
   
   
    [fileManager release];
    [pool drain];

}

0 comments:

Post a Comment

Technology blogs Blog Directory

  © Blogger template Noblarum by Ourblogtemplates.com 2009

Back to TOP