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

Categories

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

objective c - Hiding NSLog output coming from precompiled library

I am using a precompiled library I don't have the source of and it's printing a lot of debug logs. Is it possible to hide the output from just a specific library?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

No. NSLog writes its output directly to standard error without checking to see if it should. Once the function has been called, the output will be written.

Perhaps you are using a debug version of the library. Check with those who created it to see if there is, or they would be willing to create, a log-free version.

If you cannot get a version of the library without logging, you could redirect your standard error to /dev/null, which will cause NSLog output to be discarded by the system. Note that this requires you to mess with low level file descriptors, and you will discard output from all logging, not just that library. You could minimize the lost output by only redirecting when you call the library functions, but then any function or method that the library calls will also have its logs ignored. You could also redirect it at all times except for when you are logging, which means all other libraries will have their logs discarded. Since there is no way to ensure that helpful logs are not discarded (like exception messages), I would not recommend any redirection for a debug build of your application.

Here is redirecting and unredirecting would work (note that these would work as objective-c methods too):

int discardLogging() {
    static int discardedOutputFD = -1;
    if(discardedOutputFD == -1) discardedOutputFD = open("/dev/null", O_WRONLY);
    int copy = dup(2); // Duplicate the old file descriptor, so it can be restored
    dup2(discardedOutputFD, 2); // Redirect
    return copy;
}

void restartLogging(int copy) {
    dup2(copy, 2); // Redirect back
    close(copy); // Not needed anymore
}

The first function redirects standard error to /dev/null and returns a copy of the old file descriptor. The second redirects it to the copied descriptor and closes the extra copy. Warning: You should check the return values of every function called, since they map to system calls.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.7k users

...