Reputation: 2803
I am trying to redirect stdout and stderr to a log file.
/* Redirecting stderr buffer to stdout */
dup2(fileno(stdout), fileno(stderr));
/* Redirecting stdout buffer to logfile */
if((LogStream = freopen(LogPath.c_str(), "w", stdout)) == NULL)
{
cout << "Failed to redirect console logs\n";
}
.
.
. //other code
.
.
fclose(LogStream);
LogStream = freopen (NULL_LOG, "w", stdout);
This is what i am doing. But still i am missing out some of the logs. I came to know that when i executed my application commenting out these lines of code. I am dubious about this code snippet. Please provide your feedback on this.
Upvotes: 0
Views: 2398
Reputation:
first close stdout and stderr
close(STDOUT_FILENO);
close(STDERR_FILENO)
open new file to write logs to.
int file = open( "logfile", O_CREAT | O_RDWR, 0644 );
duplicate the logfile file descriptor to use with stdout and stderr. see man dup2
dup2( file, STDOUT_FILENO);
dup2( file, STDERR_FILENO);
I hope above code help you..
Upvotes: 3