I want to create two log files in my iPhone application. If I redirect the NSLog output to a file using freopen(), then all the log statements will go into one mentioned fil
Start with the Lumberjack framework: https://github.com/robbiehanson/CocoaLumberjack
I want to put some log statements into one file while some into different file
There are a couple ways to achieve this. Here's one example: Add 2 file loggers:
fileLoggerA = [[DDFileLogger alloc] init];
fileLoggerB = [[DDFileLogger alloc] init];
[DDLog addLogger:fileLoggerA];
[DDLog addLogger:fileLoggerB];
So at this point, all log statements will get directed to both fileLogger1 & fileLogger2. Next we're going to add a "filter" to each fileLogger so they ignore log statements not directed at them.
We'll do this by creating 2 different logging macros: ALog() & BLog()
fileLoggerA will only write log statements from ALog(). fileLoggerB will only write log statements from BLog().
To set this up we can take advantage of the "logging context". You could do something as simple as:
#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 more advanced than this (e.g. add support for log levels, etc) But the thing to note is how ALog has a "context" of 1, and BLog has a "context" of 2.
Now you just need to create a "custom formatter/filter". Here's an example:
- (NSString *)formatLogMessage:(DDLogMessage *)logMessage
{
if (logMessage->logContext == theContextIShouldLog)
return logMessage->logMsg;
else
return nil;
}
And, of course, add your custom formatter/filter to the file loggers:
[fileLoggerA setLogFormatter:[MyContextFilter filterWith:1]];
[fileLoggerB setLogFormatter:[MyContextFilter filterWith:2]];
More information on these topics can be found via 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 https://github.com/robbiehanson/CocoaLumberjack/wiki/CustomLogLevels