Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
654 views
in Technique[技术] by (71.8m points)

objective c - NSLog() to both console and file

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.

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.

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.

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.

UPDATE: The most important part of redirecting is to have system error logs (stderr) written to both console and file.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The way we have implemented is:

if (!isatty(STDERR_FILENO)) {
    // Redirection code
}

This is based on general assumption that if a console is attached, you do not need to store those logs in the file since you are already debugging. So whenever the console is attached, logs will be printed there, otherwise saved to a file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...