我正在使用代码将所有NSLog写入文本文件。如何选择我只需要写入文件的NSlog?
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *logPath = [documentsDirectory stringByAppendingPathComponent:@"MOVbandlog.txt"];
//freopen([logPath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
freopen([logPath fileSystemRepresentation],"a+",stderr);
答案 0 :(得分:2)
您可能需要查看Lumberjack,这是一个综合的日志记录库。
答案 1 :(得分:2)
请看看这可能有所帮助:
当设备未连接到系统时,将nslog输出重定向到文件非常有用,我们需要控制台日志来跟踪一些问题。为此,我们添加了一个NSObject的singelton类USTLogger子类:
USTLogger.h文件的源代码如下:
#import <Foundation/Foundation.h>
@interface USTLogger : NSObject
{
BOOL stdErrRedirected;
}
@property (nonatomic, assign) BOOL stdErrRedirected;
-(void) writeNSLogToFile;
+ (USTLogger *) sharedInstance;
USTLogger.m文件的源代码如下:
#import "USTLogger.h"
#import <unistd.h>
@implementation USTLogger
@synthesize stdErrRedirected;
static int savedStdErr = 0;
static USTLogger *sharedInstance;
+ (USTLogger *) sharedInstance {
static dispatch_once_t once;
static id sharedInstance;
dispatch_once(&once, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
-(id)init {
return self;
}
- (void) writeNSLogToFile
{
if (!stdErrRedirected)
{
stdErrRedirected = YES;
savedStdErr = dup(STDERR_FILENO);
NSString *cachesDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *logPath = [cachesDirectory stringByAppendingPathComponent:@"nslog.log"];
freopen([logPath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
}
}
- (void)restoreStdErr
{
if (stdErrRedirected)
{
stdErrRedirected = NO;
fflush(stderr);
dup2(savedStdErr, STDERR_FILENO);
close(savedStdErr);
savedStdErr = 0;
}
}
在实施USTLogger类之后,我们只需要在文件中需要nslog时调用这些方法
#import "AppDelegate.h"
#import "USTLogger.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[[USTLogger sharedInstance] writeNSLogToFile];
NSLog(@"didFinishLaunchingWithOptions");
return YES;
}
@end
这会将整个nslog输出写入文件并存储在应用程序文档目录中,我们可以通过启用文件共享来获取该nslog文件。
源代码可从以下链接下载:
答案 2 :(得分:1)
您可以创建两个版本的NSLog,因为仅使用NSLog的MYLog将显示在控制台上。第二个MYLogFile,它将调用NSLog并写入文件。
所以基本上你需要制作两个宏或方法。