简体   繁体   中英

How to write a log in to a text file for debugging purpose using objective C?

I want to debug the login process in my app and want to evaluate the results when developing my application.

The login process contains the basic things like user name and password and I want the result of this and the other credentials to be stored in a file.

So how to accomplish this while developing the application and not using the breakpoints all the time.

Thank you.

Without knowing more, NSLog will likely do.


Ahh... OK. This'll do what you want (boiler plate anyway) while continuing to support full on NSString formatting.

.... somewhere, declare a global ....

NSFileHandle *logFile = nil;

... initialization code ....

logFile = [NSFileHandle fileHandleForWritingAtPath: ...string containing path...];

... the actual log function ....

void MyLog(NSString *format, ...) {
    va_list args;
    va_start(args, format);
    NSString *formattedString = [[NSString alloc] initWithFormat: format
                                                  arguments: args];
    va_end(args);
    [logFile writeData: [formattedString dataUsingEncoding: NSNEXTSTEPStringEncoding]];
    [formattedString release];
}

you could redirect the stderr (this is where NSLog puts its messages) to a file.

+ (void)redirectNSLogToFile {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *logPath = [documentsDirectory stringByAppendingPathComponent:@"console.log"];
    freopen([logPath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
}
NSError *error;
NSMutableString *logstr = [ [NSMutableString alloc] init ];

// write info to logstr here

[ logstr writeToFile:@"file.log" atomically:YES encoding:NSUnicodeStringEncoding error:&error ];

你可以看看Log4Cocoa

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM