Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to NSLog into a file

Is it possible to write every NSLog not only into console, but into a file too? I want to prepare this without replacing NSLog into someExternalFunctionForLogging.

It will be real problem to replace all NSLog. Maybe there is possibility for parsing data from console or catching messages?

like image 258
Vov4yk Avatar asked Sep 01 '11 14:09

Vov4yk


People also ask

Where does NSLog write to?

NSLog outputs messages to the Apple System Log facility or to the Console app (usually prefixed with the time and the process id).

How do I create a log file in Swift?

The function getDocumentsDirectory will return the url of documents directory. You can store all your logs into fileContent variable and then pass it to writeToFile function in your applicationWillTerminate function . inside Appdelegate. Now you have all your logs into your Log file.


2 Answers

Option 1: Use ASL

NSLog outputs log to ASL (Apple's version of syslog) and console, meaning it is already writing to a file in your Mac when you use the iPhone simulator. If you want to read it open the application Console.app, and type the name of your application in the filter field. To do the same in your iPhone device, you would need to use the ASL API and do some coding.

Option 2: write to a file

Let's say you are running on the simulator and you don't want to use the Console.app. You can redirect the error stream to a file of your liking using freopen:
freopen([path cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
See this explanation and sample project for details.

Or you can override NSLog with a custom function using a macro. Example, add this class to your project:

// file Log.h #define NSLog(args...) _Log(@"DEBUG ", __FILE__,__LINE__,__PRETTY_FUNCTION__,args); @interface Log : NSObject void _Log(NSString *prefix, const char *file, int lineNumber, const char *funcName, NSString *format,...); @end  // file Log.m #import "Log.h" @implementation Log void _Log(NSString *prefix, const char *file, int lineNumber, const char *funcName, NSString *format,...) {     va_list ap;     va_start (ap, format);     format = [format stringByAppendingString:@"\n"];     NSString *msg = [[NSString alloc] initWithFormat:[NSString stringWithFormat:@"%@",format] arguments:ap];        va_end (ap);     fprintf(stderr,"%s%50s:%3d - %s",[prefix UTF8String], funcName, lineNumber, [msg UTF8String]);     [msg release]; } @end 

And import it project wide adding the following to your <application>-Prefix.pch:

#import "Log.h" 

Now every call to NSLog will be replaced with your custom function without the need to touch your existing code. However, the function above is only printing to console. To add file output, add this function above _Log:

void append(NSString *msg){     // get path to Documents/somefile.txt     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);     NSString *documentsDirectory = [paths objectAtIndex:0];     NSString *path = [documentsDirectory stringByAppendingPathComponent:@"logfile.txt"];     // create if needed     if (![[NSFileManager defaultManager] fileExistsAtPath:path]){         fprintf(stderr,"Creating file at %s",[path UTF8String]);         [[NSData data] writeToFile:path atomically:YES];     }      // append     NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:path];     [handle truncateFileAtOffset:[handle seekToEndOfFile]];     [handle writeData:[msg dataUsingEncoding:NSUTF8StringEncoding]];     [handle closeFile]; } 

and add this line below fprintf in the _Log function:

append(msg); 

File writing also works in your iPhone device, but the file will be created in a directory inside it, and you won't be able to access unless you add code to send it back to your mac, or show it on a view inside your app, or use iTunes to add the documents directory.

like image 92
Jano Avatar answered Oct 07 '22 06:10

Jano


There is a far easier approach. Here is the method that redirects NSLog output into a file in application’s Documents folder. This can be useful when you want to test your app outside your development studio, unplugged from your mac.

ObjC:

- (void)redirectLogToDocuments  {      NSArray *allPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);      NSString *documentsDirectory = [allPaths objectAtIndex:0];      NSString *pathForLog = [documentsDirectory stringByAppendingPathComponent:@"yourFile.txt"];       freopen([pathForLog cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr); } 

Swift:

// 1. Window > Devices and Simulators // 2. Select the device // 3. Select your app and click gear icon // 4. Download container // 5. Right click and "view contents" // 6. Find "yourfile.log" under Downloads // // redirectLogToDocuments()  func redirectLogToDocuments() {   let allPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)   let documentsDirectory = allPaths.first!   let pathForLog = "\(documentsDirectory)/yourfile.log"   freopen(pathForLog.cString(using: String.Encoding.ascii)!, "a+", stdout) } 

After executing this method all output generated by NSLog (ObjC) or print (Swift) will be forwarded to specified file. To get your saved file open Organizer, browse application’s files and save Application Data somewhere in your file system, than simply browse to Documents folder.

like image 45
Rafa de King Avatar answered Oct 07 '22 05:10

Rafa de King