Chitika

Thursday, October 20, 2011

C++: Instant append of log messages to the file

Logging utility required log messages to be appended at once at end of file so that the utilities like tail, can show the current/latest output.

In CLogFile::SetFileDescriptorToFile object method, setbuf API is used with argument of NULL, to set file output operation as unbuffered output just like stderr.

void SetFileDescriptorToFile(char *filename) {
if(NULL != this->FileDescriptor &&
stdout != this->FileDescriptor &&
stderr != this->FileDescriptor) {
fclose(this->FileDescriptor);
}

........

if((this->FileDescriptor=fopen(name, "a+")) == NULL) {
this->FileDescriptor=stderr;
throw "Can not open logfile";
}
else {
setbuf(this->FileDescriptor, NULL);
}

}

No comments:

Post a Comment