NSLog()到控制台和文件 [英] NSLog() to both console and file
问题描述
我想将NSog()
重定向到文件,但仍要在控制台中查看输出.
我知道stderr
可以使用以下命令重定向到文件:
I would like to redirect NSog()
to file, but still to see the output in console.
I am aware that stderr
can be redirected to file using:
freopen("file.log", "a+", stderr);
但是将其重定向到文件后,该日志不再显示在控制台输出中.
but after redirecting it to file, the log is no more shown in the console output.
我可以在NSLog()
周围构建自定义包装,但是在应用程序崩溃时,不会获得写入到stderr
的已记录崩溃日志.
I could build a custom wrapper around NSLog()
but I would not get logged crash logs that are written to stderr
in the moment of app crash.
我也在尝试使用dup()
和其他方法来复制文件描述符,但是输出是在文件或控制台中的以太,两者都不是.
I was also experimenting with dup()
and other methods for duplicating file descriptors, but the output was ether in file or in console, never in both.
在这里提出了类似的问题: 在iPhone上将stderr写入文件和控制台 但没有被接受的答案,也没有建议使用NSLog()包装器.
Similar questions was asked here: Write stderr on iPhone to both file and console but without accepted answer, or with suggestion to use a NSLog() wrapper.
有人对如何管理这项工作有想法吗? 提前感谢.
Has anyone an idea on how to manage this work? Thanx in advance.
更新:重定向最重要的部分是将系统错误日志( stderr )写入控制台和文件.
UPDATE: The most important part of redirecting is to have system error logs (stderr) written to both console and file.
推荐答案
According to the docs, you will need a custom log facility.
您至少需要一个函数,该函数接受可变参数并打印到NSLog和fprintf中,例如:
You need at a minimum, a function that takes variadic arguments and printd to NSLog and fprintf, something like:
void myLog(NSString* format, ...)
{
va_list argList;
va_start(argList, format);
NSString* formattedMessage = [[NSString alloc] initWithFormat: format arguments: argList];
va_end(argList);
NSLog(@"%@", formattedMessage);
fprintf(myFileDescriptor, "%s\n", [formattedMessage UTF8String]);
[formattedMessage release]; // if not on ARC
}
或者有可可记录框架.
这篇关于NSLog()到控制台和文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!