Writing to event log in c

Here is a sample code in c of writing logs to the event viewer

Possible event types:


#define LOG_SUCCESS 0
#define LOG_ERROR 1
#define LOG_WARNING 2
#define LOG_INFORMATION 4

The function that writes the log itself is ReportEvent or ReportEventW:


void Log(const LPCWSTR msg,
	const int a_type)
{
	DWORD event_id = 1;

	HANDLE h_event_log = RegisterEventSource(0, L"MyEventSource");

	if (0 == h_event_log)
	{
		
	}
	else
	{
		if (FALSE == ReportEvent(h_event_log,
			a_type,
			0,
			event_id,
			0,
			1,
			0,
			&msg,
			0))
		{
			
		}

		DeregisterEventSource(h_event_log);
	}
}

It is better to create some warpper around it, so it will be similar to printf with formatting


void LogFormat(int atype, wchar_t * msg, ...) {
	wchar_t str[256];

	va_list argptr;
	va_start(argptr, msg);

	vswprintf_s(str, 256, msg, argptr);

	va_end(argptr);

	Log(str, atype);	
}

And if there is a need to convert between char* to wchar_t* use this:


const void ConvertToWchar(const char* c, const wchar_t* w)
{
	const size_t cSize = strlen(c) + 1;
	size_t converted;
	mbstowcs_s(&converted, w, cSize, c, 256);
}

Post a Comment

Previous Post Next Post