Log to event viewer on Windows with C++

Leonardo Alves Machado picture Leonardo Alves Machado · May 4, 2016 · Viewed 9.3k times · Source

I want to use log on my C++ application. However, I'd like to use Windows (10) event viewer, instead of text files. I found out some weird calls, that I don't even know what the parameters mean - ReportEvent, OpenEventLog and some other Event Logging functions. I also can't use managed code, due to some limitations on my app.

I've also tried to use the code on this link, but I get compilation errors (namespace 'System' undefined - it seems some include files are missing...).

I found no sample code that works yet.

I would appreciate a sample code, if possible - just a simple logging from a local application, built in non managed C++. Can someone help?

Answer

Donnie picture Donnie · May 4, 2016

Your link doesn't compile because that's managed C++ (note the use of gcnew)

If all you want to write are strings it's easy, all you need is RegisterEventSource and ReportEvent.

It's approximately this:

const char* custom_log_name = "MyLogName";

// create registry keys for ACLing described on MSDN: http://msdn2.microsoft.com/en-us/library/aa363648.aspx

HANDLE event_log = RegisterEventSource(NULL, custom_log_name);
const char* message = "I'm in an event log";
ReportEvent(event_log, EVENTLOG_SUCCESS, 0, 0, NULL, 1, 0, &message, NULL);

This only allows for logging strings. Much more complex (and useful) logging is possible, but it's fairly involved in straight C++. If you can write managed code for your logging component it becomes easier to deal with.