请看看这可能会有所帮助:
当设备未连接到系统时,将 nslog 输出重定向到文件在场景中很有用,我们需要控制台日志来跟踪一些问题。为了做到这一点,我们添加了一个 NSObject 的单格类 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 文件。
源代码可从以下链接下载:
https://shankertiwari3.wordpress.com/2015/06/09/redirect-the-nslog-output-to-file-instead-of-console/