Create multiple log files in an iPhone application

I want to create two log files in an application for iPhone. If I redirect the output of NSLog to a file using the freopen () function, then all the log statements will go into one of the mentioned files.
But I want to put some log statements in one file, and some in another file.

Any idea how I can do this?

+3
source share
2 answers

A better approach would be to write your own log class as a replacement that you use instead of NSLog (). This way you can easily determine at runtime which logs should be written to the file. A custom class can use NLog () to write to the console at the same time. This seems like the best approach, since freopen() just redirects all the log output.

+2
source

Start with the Lumberjack framework: https://github.com/robbiehanson/CocoaLumberjack

I want to put some log statements in one file and some in another file

There are several ways to achieve this. Here is one example: Add 2 file registrars:

 fileLoggerA = [[DDFileLogger alloc] init]; fileLoggerB = [[DDFileLogger alloc] init]; [DDLog addLogger:fileLoggerA]; [DDLog addLogger:fileLoggerB]; 

So, at this moment all the log statements will be directed both to the Logger1 file and to the Logger2 file. Then we add a “filter” to each file archive so that they ignore the log statements that are not directed at them.

We will do this by creating 2 different logging protocols: ALog () and BLOG ()

fileLoggerA will only write log entries from ALog (). fileLoggerB will only write log entries from BLOG ().

To establish this, we can use the "logging context". You can do something simple:

 #define ALog(frmt, ...) SYNC_LOG_OBJC_MACRO(0, 0, 1, frmt, ##__VA_ARGS__) #define BLog(frmt, ...) SYNC_LOG_OBJC_MACRO(0, 0, 2, frmt, ##__VA_ARGS__) 

Obviously, you can get a more advanced level (for example, add support for log levels, etc.). But it should be noted that ALOG has a “context” of 1, while BLOG has a “context” of 2.

Now you just need to create a "custom formatter / filter." Here is an example:

 - (NSString *)formatLogMessage:(DDLogMessage *)logMessage { if (logMessage->logContext == theContextIShouldLog) return logMessage->logMsg; else return nil; } 

And, of course, add your own formatterter / filter to the file loggers:

 [fileLoggerA setLogFormatter:[MyContextFilter filterWith:1]]; [fileLoggerB setLogFormatter:[MyContextFilter filterWith:2]]; 

More information on these topics can be found on the Lumberjack project pages:

https://github.com/robbiehanson/CocoaLumberjack/wiki/GettingStarted https://github.com/robbiehanson/CocoaLumberjack/wiki/CustomFormatters https://github.com/robbiehanson/CocoaLumberjack/wiki/CustomContext .com / robbiehanson / CocoaLumberjack / wiki / CustomLogLevels

+14
source

All Articles