是否可以将每个 NSLog
不仅写入控制台,还写入文件?我想准备这个而不将 NSLog
替换为 someExternalFunctionForLogging
。
替换所有NSLog
将是真正的问题。也许有可能从控制台解析数据或捕获消息?
最佳答案
选项 1:使用 ASL
NSLog 将日志输出到 ASL(Apple 的 syslog 版本)和控制台,这意味着当您使用 iPhone 模拟器时,它已经写入您 Mac 中的文件。如果您想阅读它,请打开应用程序 Console.app,然后在过滤器字段中输入应用程序的名称。要在您的 iPhone 设备上执行相同操作,您需要使用 ASL API 并进行一些编码。
选项 2:写入文件
假设您在模拟器上运行并且不想使用 Console.app。您可以使用 freopen 将错误流重定向到您喜欢的文件:
freopen([path cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
看到这个explanation and sample project了解详情。
或者您可以使用宏使用自定义函数覆盖 NSLog。例如,将此类添加到您的项目中:
// file Log.h
#define NSLog(args...) _Log(@"DEBUG ", __FILE__,__LINE__,__PRETTY_FUNCTION__,args);
@interface Log : NSObject
void _Log(NSString *prefix, const char *file, int lineNumber, const char *funcName, NSString *format,...);
@end
// file Log.m
#import "Log.h"
@implementation Log
void _Log(NSString *prefix, const char *file, int lineNumber, const char *funcName, NSString *format,...) {
va_list ap;
va_start (ap, format);
format = [format stringByAppendingString:@"\n"];
NSString *msg = [[NSString alloc] initWithFormat:[NSString stringWithFormat:@"%@",format] arguments:ap];
va_end (ap);
fprintf(stderr,"%s%50s:%3d - %s",[prefix UTF8String], funcName, lineNumber, [msg UTF8String]);
[msg release];
}
@end
并在项目范围内导入它,将以下内容添加到您的 <application>-Prefix.pch
:
#import "Log.h"
现在对 NSLog 的每次调用都将替换为您的自定义函数,而无需触及您现有的代码。但是,上面的功能只是打印到控制台。要添加文件输出,在_Log上面添加这个函数:
void append(NSString *msg){
// get path to Documents/somefile.txt
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"logfile.txt"];
// create if needed
if (![[NSFileManager defaultManager] fileExistsAtPath:path]){
fprintf(stderr,"Creating file at %s",[path UTF8String]);
[[NSData data] writeToFile:path atomically:YES];
}
// append
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:path];
[handle truncateFileAtOffset:[handle seekToEndOfFile]];
[handle writeData:[msg dataUsingEncoding:NSUTF8StringEncoding]];
[handle closeFile];
}
并在 _Log 函数中的 fprintf 下面添加这一行:
append(msg);
文件写入也适用于您的 iPhone 设备,但该文件将在其中的目录中创建,您将无法访问,除非您添加代码将其发送回您的 Mac,或将其显示在查看您的应用程序内部,或使用 iTunes 添加文档目录。
关于ios - 如何 NSLog 进入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7271528/