是否有可能在C中合并stderr和stdout?

dav*_*vid 3 c cocoa stdout stderr

我需要合并stderr和stdout,因为我希望我的调试和异常在同一个日志文件中.我试过了

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

但这搞砸了秩序.它会在文件顶部打印stderr消息.或者有更好的方法登录可可吗?NSLog只是阻塞了syslog:P

编辑:尝试我的日志宏:

#ifdef DEBUG_MODE_LEVEL_KEEP
#define DLogK(...) (void)printf("%s: %s\n",  __PRETTY_FUNCTION__, [[NSString    stringWithFormat:__VA_ARGS__] UTF8String])
#else
#define DLogK(...)
#endif
Run Code Online (Sandbox Code Playgroud)

如果我只是将stderr重定向到日志文件并使用

fprintf(stderr, "%s: %s\n",  __PRETTY_FUNCTION__, [[NSString    stringWithFormat:__VA_ARGS__] UTF8String])
Run Code Online (Sandbox Code Playgroud)

它也不起作用.这不应该只是工作吗?

谢谢

Jas*_*son 8

使用dup2()in unistd.h,您可以关闭它们stderr并将stdout它们重定向到文件.例如:

#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");
}
Run Code Online (Sandbox Code Playgroud)

现在,两者stderrstdout使用时都将写入my_log_file.txt.虽然我不确定iOS,但这应该可以在OSX上完美运行.


Dav*_*nan 7

当您运行该过程时,将stderr重定向到stdout,如下所示:

myprocess 2>&1
Run Code Online (Sandbox Code Playgroud)