请看看这可能会帮助:
重定向当设备没有连接到系统的NSLog输出到文件中scenerios有用的,我们需要的控制台日志跟踪了一些issues.In为了做到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类的实现,我们只需要调用这些方法时,我们需要在文件
#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,我们可以通过为应用程序启用文件共享来获得该nslog文件。
源代码从下面的链接下载:
https://shankertiwari3.wordpress.com/2015/06/09/redirect-the-nslog-output-to-file-instead-of-console/
我能得到一个例子吗?这是我的一个NSlog NSLog(@“\ n ********* data from device ******** \ n%@”,[data description]); – TWcode 2013-03-27 01:07:43
做一些调整[这里](http://stackoverflow.com/questions/9619708/nslog-to-both-console-and-file) – 2013-03-27 01:20:36
这行不行:fprintf(myFileDescriptor,“%s \ n”,[ formattedMessage UTF8String]);有关myfileDescriptor的信息 – TWcode 2013-03-27 01:40:23