开发者

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

开发者 https://www.devze.com 2023-01-24 18:06 出处:网络
I want to debug the login process in my app and want to evaluate the results when developing my application.

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开发者_JS百科 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 ];


You could take a look at Log4Cocoa.

0

精彩评论

暂无评论...
验证码 换一张
取 消