Logging is important for applications. In this paper, a simple implementation of the implementation of such a module. The module realizes the function of recording the information expected by the program. The module opens a thread for each module it registers with and creates or opens a text file with the same name with the name extension. log, located under the/log subdirectory of the program executable directory. This also has some flexibility, such as the debug version can be used to output debugging information to the file, and in release version is really used to record log information.
The following is an introduction to the interfaces of the two classes:
Cinforeport:
The class was implemented with the AFX_EXT_CLASS keyword and is a DLL export class inherited from CObject.
Data members:
// 存放线程的指针链表,所有对象公用一份,故声明为static
static CPtrList m_lstpThreads;
member functions:
// 注册模块
DWORD Register(LPCTSTR ModuleNameToReg);
// 写入信息,其中的第一个参数MoudleID必须是Register函数的返回值,
// 如果为NULL则将信息记录到FatalErr.log文件中。
void WriteInfo(DWORD MoudleID, CString InfoDescribe);
// 写入信息,其中的第一个参数MoudleID必须是Register函数的返回值,
// 如果为NULL则将信息记录到FatalErr.log文件中。
void WriteInfo(DWORD MoudleID, CString InfoFrom, CString InfoDescribe);
Cwriteinfo:
This class inherits from CWinThread, which opens a thread for each registered module and maintains a log file with the extension log. Because there may be multiple threads doing the same file operation at the same time, the class also provides a mutex mechanism to ensure that file I/O is not conflicting.
Data members:
// 注册的模块名,日志文件与它同名但扩展名不同
CString m_strModuleName;
CFile m_file; // 日志文件对象
// 为实现文件互斥操作的事件句柄
HANDLE m_hEventBusy;
member functions:
// GetName()和SetModuleFileName()对私有成员m_strModuleName进行存取。
CString GetName();
void SetModuleFileName(CString strFileName);
Message handler function:
// 处理由CInfoReport::WriteInfo()发来的消息TM_WRITE_INFO
afx_msg void OnWriteInfo(WPARAM wParam, LPARAM lParam);
Note: Please refer to the source code, including the library itself and a test program inforeporttest. For simplicity, the OnDraw () function of the view class of the test program (a document/visual SDI program) calls the library's logging function.
Where the program needs to be perfected
The program completes in a hurry and the problem is not resolved:
1. Security checks, such as the executable file in the directory without/log subdirectories, the program will produce an exception.
2. The export class of the program is not a problem in the EXE file as a global variable, and in the DLL as a global variable application will cause no response, trace discovery is due to the creation of a new thread at:: WaitForSingleObject () at the zombie, As a local variable (the class's member variable is used with no problems).
This article supporting source code