NSLog 输出到文件,或 iOS 的外部日志记录功能

发布于 2024-08-13 20:24:10 字数 426 浏览 7 评论 0原文

我希望能够将 NSLog 的内容写入我指定的文件,或者我需要一个将日志写入文件的函数,例如:

WriteLog(@"some activity by the user");
WriteLog(@"some more activity by the user");

但我希望输出如下所示:

12-25-2009 1:30:00PM some activity by the user
12-25-2009 1:35:00PM some more activity by the user

有谁知道我该怎么做吗?请注意,我需要在行开头提供日期和时间。

另外,由于某种原因,freopen不会向文件写入任何数据,它会创建文件,只是没有输出!

I want to be able to write the contents of NSLog to a file I specify, or I need a function that writes a log to a file, for example:

WriteLog(@"some activity by the user");
WriteLog(@"some more activity by the user");

but I want the output to look like this:

12-25-2009 1:30:00PM some activity by the user
12-25-2009 1:35:00PM some more activity by the user

does anyone know how I can do this? Note that I need the date and time at the beginning of the line.

Also, for some reason, freopen will not write any data to the file, it will create the file, just no output!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏花。依旧 2024-08-20 20:24:10

我将自己的日志写入文件类,但我发现在绝大多数情况下,复制调试器控制台的内容,将其粘贴到文件中并在必要时使用编辑或脚本来处理它会更容易。即使对于非常大的转储,这也很有效。我什至曾经这样扔过桌子。这虽然不优雅,但是比处理文件要快得多,而且更不容易出错。

I wrote my own log to file class but I discovered that in the vast majority of cases it was easier to just copy the contents of the debugger console,paste it to a file and use editing or scripts to process it if necessary. That works well even for very large dumps. I've even dumped tables that way. It's inelegant but way, way quicker and less error prone than futzing with files.

鸠魁 2024-08-20 20:24:10

NSLog 并不能真正让您自定义其输出的位置,因此您最好推出自己的日志记录功能。就我个人而言,我会使用 log_finelog_info 风格并使用类似 NSString 的 writeToFile 方法:

[log_string writeToFile:@"log.log" atomically:YES encoding:NSUTF8StringEncoding error:NULL];

唯一的问题是使用原子选项可能会影响性能,所以这可能是一个更好的选择解决方案:

NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:"log.log"];
[output seekToEndOfFile];
[output writeData:[log_string dataUsingEncoding:NSUTF8StringEncoding]];

关于格式化日期/时间,请参见NSDateFormatter类。

Well NSLog doesn't really let you customize where its output goes, so you are best off rolling your own logging functions. Personally I would go with the log_fine, log_info style and use something like NSString's writeToFile method:

[log_string writeToFile:@"log.log" atomically:YES encoding:NSUTF8StringEncoding error:NULL];

Only problem is using the atomic option could affect the performance, so this may be a better solution:

NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:"log.log"];
[output seekToEndOfFile];
[output writeData:[log_string dataUsingEncoding:NSUTF8StringEncoding]];

As for formatting the date/time, see the NSDateFormatter class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文