Skip to content

Commit

Permalink
simpleLog add redirection of stdout/stderr to custom FDs (#32)
Browse files Browse the repository at this point in the history
  • Loading branch information
sy-c authored and Barthelemy committed Aug 27, 2019
1 parent 6fd47a6 commit 1463358
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 11 deletions.
3 changes: 3 additions & 0 deletions include/Common/SimpleLog.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ class SimpleLog {
// \param logFilePath Path to log file. If NULL, using stdout/stderr.
int setLogFile(const char* logFilePath=NULL);

// Change file descriptors used for stdout/stderr with provided ones
// They must be valid for the lifetime of this object (or until overwritten), and are not closed.
void setFileDescriptors(int fdStdout, int fdStderr);

enum FormatOption : int {
ShowTimeStamp = 0x1,
Expand Down
36 changes: 25 additions & 11 deletions src/SimpleLog.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#include <time.h>
#include <sys/time.h>
#include <unistd.h>

class SimpleLog::Impl {
public:
Expand All @@ -24,7 +25,9 @@ class SimpleLog::Impl {
protected:
FILE *fp; // descriptor to be used. If NULL, using stdout/stderr.
int formatOptions;

int fdStdout;
int fdStderr;

friend class SimpleLog;
};

Expand All @@ -33,6 +36,8 @@ SimpleLog::Impl::Impl() {
formatOptions = SimpleLog::FormatOption::ShowTimeStamp
| SimpleLog::FormatOption::ShowSeveritySymbol
| SimpleLog::FormatOption::ShowMessage;
fdStdout = fileno(stdout);
fdStderr = fileno(stderr);
}

SimpleLog::Impl::~Impl() {
Expand All @@ -46,7 +51,7 @@ SimpleLog::Impl::~Impl() {
int SimpleLog::Impl::logV(SimpleLog::Impl::Severity s, const char *message, va_list ap)
{
char buffer[1024] = "";
size_t len = sizeof(buffer);
size_t len = sizeof(buffer) - 2;
size_t ix = 0;

if (formatOptions & SimpleLog::FormatOption::ShowTimeStamp) {
Expand Down Expand Up @@ -95,20 +100,23 @@ int SimpleLog::Impl::logV(SimpleLog::Impl::Severity s, const char *message, va_l
ix+=vsnprintf(&buffer[ix], len-ix, message, ap);
if (ix>len) { ix=len; }
}


buffer[ix] = '\n';
ix++;
buffer[ix]=0;

FILE *fpOut=stdout;

if (fp==NULL) {
int fd;
if (fp != NULL) {
fd = fileno(fp);
} else {
if (s==Severity::Error) {
fpOut=stderr;
fd = fdStderr;
} else {
fd = fdStdout;
}
} else {
fpOut=fp;
}
fprintf(fpOut,"%s\n", buffer);
fflush(fpOut);
write(fd, buffer, ix);

return 0;
}

Expand Down Expand Up @@ -182,4 +190,10 @@ void SimpleLog::setOutputFormat(int opts) {
pImpl->formatOptions=opts;
}

void SimpleLog::setFileDescriptors(int fdStdout, int fdStderr)
{
pImpl->fdStdout = fdStdout;
pImpl->fdStderr = fdStderr;
}

/// \todo: thread to flush output every 1 second

0 comments on commit 1463358

Please sign in to comment.