Monday, December 29, 2008

[VC++] Writing event log to Event Viewer

You might have viewed the event logs (Start->Run->eventvwr), but have you ever tried writing the logs to the event viewer ? If you are interested to do the same, then following are the APIs which will help you,
RegisterEventSource() // For registering event source
ReportEvent() // For writing event log
DeregisterEventSource() // Release the event log handle

Below code snippet will write application event log to event viewer and will give you a better idea.
// Register event source.
HANDLE hEventLog = RegisterEventSource( 0,"Test Evt Logger");
// No CategoryWORD
wCategoryID = 0;
// Event ID in the message file associated with the event source
DWORD dwEventID = 1000;
// No security attributes set
PSID pSecurity = 0;
// No of strings to be logged
WORD wNumofStrs = 2;
// No raw data so size is 0
DWORD dwDataSize = 0;
// No raw data
LPVOID* lpRawData = 0;
// Strings to be logged to event viewer
LPCTSTR LogStrings[] = { "First string to event viewer", "Second string to event viewer" };
// Logging string to event viewer with type information
if( !ReportEvent( hEventLog, EVENTLOG_INFORMATION_TYPE, wCategoryID, dwEventID, pSecurity, wNumofStrs, dwDataSize, LogStrings, lpRawData ))
{
// Failed reporting event
}
// Closes the handle to the specified event log
DeregisterEventSource( hEventLog );

Below snapshot shows the output of the above code,

No comments: