Results 1 to 3 of 3
I'm coding a small function (in C++) to write entries to a logfile, and I need some advice. When, and where, should I open the logfile? Currently, I'm opening the ...
- 10-09-2007 #1Just Joined!
- Join Date
- Oct 2007
- Posts
- 3
When to open logfile?
I'm coding a small function (in C++) to write entries to a logfile, and I need some advice. When, and where, should I open the logfile? Currently, I'm opening the logfile in the logging function. It seems inefficient to me, since I open the logfile each time I call the "log" function, then close the file. Is there a better way to do this?
Here is the code snippet (for the sake of brevity, I stripped out the timestamping code):
---------------------------------------------------
void log(string logentry)
{
ofstream logfile;
logfile.open ("/tmp/test.log", ios::app);
logfile << logentry << "\n";
logfile.close();
}
int main()
{
log("log entry text");
return 0;
}
---------------------------------------------------
- 10-09-2007 #2
Open the logfile once, near the beginning of program execution. Make the ofstream object a global. Each time just after you've written to the logfile, instead of
do this:Code:logfile.close();
Alternatively, you can write to the log file thus:Code:logfile.flush();
Either way, you can see the data in the log file immediately if, say, you're doing aCode:logfile << logentry << "\n" << flush;
at the shell command line at another console while your program's running.Code:tail -f /tmp/test.log
At program exit, the log file will close automatically.
Incidentally, have you considered putting a date/time stamp just before the logentry on each line? You could do that in this logging function.
Hope this helps.
- 10-09-2007 #3Just Joined!
- Join Date
- Oct 2007
- Posts
- 3
Your answer does help. Thanks!
I stripped out the timestamp code, just so it was easier to focus on the logging question. Here's the complete function:
void log(string logentry)
{
ofstream logfile;
logfile.open ("/tmp/testfile", ios::app);
temp = time(NULL);
timeptr = localtime(&temp);
rc = strftime(s,sizeof(s),"[ %a %b %d - %T ]: ", timeptr); // CONSTRUCT TIME STRING.
logfile << s << logentry << "\n";
logfile.close();
}
int main(void)
{
log("logfile entry text.");
return 0;
}
So, the log entry looks like:
[ Tue Oct 09 - 17:20:21 ]: log entry text.
I'm up for any ideas on how to clean this up. I originally tried ctime to get the time string, but ctime sticks a newline at the end of the time string, so it horked up the formatting.
Thanks again for your help.


Reply With Quote
