請看看這可能會幫助:
重定向當設備沒有連接到系統的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