Introduction
Sometimes, we need to record something after we give the software to our customers, so when something bad happens, we can find it out without the debug environment. Sometimes, we want to get some trace information in the release mode of the program. In these circumstances, a logfile is useful.
There are lots of logfile code examples here on The Code Project and elsewhere. This one is very simple, compared to some of the others.
Using the Code
Code is very simple. All you need is to create you CLogFile variable, open the log file and then write in it:
CFileLog log;
log.OpenFile( "myLog.log" );
log.Write( "La variable a vale: %d", a );
Features
- Does not depend on MFC or ATL
- File name could use absolute path or just the name, in which case the file will be created at the same place with the binary module, no concern with current directory, which always brings me trouble.
- Every log line has a time stamp attached, with million seconds.
- Uses
printf like format to write log lines
- Multi thread safe
Code Example
With this code, you can have a log folder for every different year and month.
CString name;
SYSTEMTIME systime;
GetLocalTime(&systime);
name.Format( "LOG\\Year_%i\\Month_%02i\\log_%02i%02i%02i.txt",
systime.wYear,
systime.wMonth,
systime.wYear,
systime.wMonth,
systime.wDay );
m_log.ChangeFile(name);
Remember: File name does not want ".\" or "\" at the beginning if you want to use relative path to application folder.
History
- 26 Jun 2002 - Initial revision
- 20 Mar 2003 - updated by Zoltan
- 10 Feb 2009 - update by Myzhar
- Modified code to avoid using
CString MFC class in Zoltan's CreateDirectories function