Is it possible to merge stderr and stdout into C?


I need to merge stderr and stdout because I want my debug and the exceptions in the same log file. I tried

    NSString *logPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Tag Monster/log.log"];
    freopen([logPath fileSystemRepresentation], "a", stderr);
    freopen([logPath fileSystemRepresentation], "a", stdout);

but this messes up the order. It prints the stderr messages at the top of the file. Or is there a better way to log in cocoa? NSLog just spams the syslog :P

Edit: Thants my log macro:

#define DLogK(...) (void)printf("%s: %s\n",  __PRETTY_FUNCTION__, [[NSString    stringWithFormat:__VA_ARGS__] UTF8String])
#define DLogK(...)

If I just redirect stderr to a logfile and log with

fprintf(stderr, "%s: %s\n",  __PRETTY_FUNCTION__, [[NSString    stringWithFormat:__VA_ARGS__] UTF8String])

it does not work either. Shouldn't that just work?


Using dup2() in unistd.h, you could close both stderr and stdout and re-direct them to a file. For instance:

#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h> 

int log_file;
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;

log_file = open("my_log_file.txt", O_WRONLY | O_CREAT, mode);

if (dup2(log_file, fileno(stderr)) != fileno(stderr) ||
    dup2(log_file, fileno(stdout)) != fileno(stdout))
    perror("Unable to redirect output");

Now both stderr and stdout, when used, will write to my_log_file.txt. While I'm not sure about iOS, this should work perfectly fine on OSX.