Click here to Skip to main content
15,441,508 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
/** @file EventsLogger.cpp
*  @brief Function Definitions for EventsLogger
*
*  @date   21-09-2013
*
*  @version 1.0
*
*  @author Dhawal Arora Danekhail, Programmer
*
*/

/**
* Header File
*/

#include "EventsLogger.h"

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Initializes the Event and Member Functions
//

DWORD InitializeEvent()
{
    //
    // Local Variables
    //

    DWORD status = ERROR_SUCCESS;
    EVT_HANDLE hSubscription = NULL;
    LPWSTR pwsPath = L"Application";
    LPWSTR pwsQuery = L"*";
    HANDLE aWaitHandles[2];
    DWORD dwWait = 0;

    //
    // Beginning of functional Logic
    //

    for (;;)
    {
        //
        // Handle for Console Input
        //

        aWaitHandles[0] = GetStdHandle(STD_INPUT_HANDLE);
        if (INVALID_HANDLE_VALUE == aWaitHandles[0])
        {
            printf("GetStdHandle failed with %u.\n", GetLastError());
            break;
        }

        //
        // Handle to a manual reset event object
        //
        aWaitHandles[1] = CreateEvent(NULL, TRUE, TRUE, NULL);
        if (NULL == aWaitHandles[1])
        {
            printf("CreateEvent failed with %u.\n", GetLastError());
            break;
        }

        //
        // Subscribe to events.
        //
        hSubscription = EvtSubscribe(NULL, aWaitHandles[1], pwsPath, pwsQuery, NULL, NULL, NULL, EvtSubscribeStartAtOldestRecord);
        if (NULL == hSubscription)
        {
            status = GetLastError();

            if (ERROR_EVT_CHANNEL_NOT_FOUND == status)
                printf("Channel %s was not found.\n", pwsPath);
            else if (ERROR_EVT_INVALID_QUERY == status)
                printf("The query %s was not found.\n", pwsQuery);
            else
                printf("EvtSubscribe failed with %u.\n", status);

            break;
        }

        printf("Press any key to quit.\n");

        //
        // Loop until the user presses a key
        //
        while (true)
        {
            dwWait = WaitForMultipleObjects(sizeof(aWaitHandles)/sizeof(HANDLE), aWaitHandles, FALSE, INFINITE);

            if (0 == dwWait - WAIT_OBJECT_0)
            {
                if (IsKeyEvent(aWaitHandles[0]))
                    break;
            }
            else if (1 == dwWait - WAIT_OBJECT_0)
            {
                if (ERROR_NO_MORE_ITEMS != (status = EnumerateResults(hSubscription)))
                {
                    break;
                }

                ResetEvent(aWaitHandles[1]);
            }
            else
            {
                if (WAIT_FAILED == dwWait)
                {
                    printf("WaitForSingleObject failed with %u\n", GetLastError());
                }
                break;
            }
        }
        //
        // Final Break Point
        //

        break;
    }

    //
    // Clean up
    //
    if (hSubscription)
        EvtClose(hSubscription);

    if (aWaitHandles[0])
        CloseHandle(aWaitHandles[0]);

    if (aWaitHandles[1])
        CloseHandle(aWaitHandles[1]);

    return 0;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Enumerate the events in the result set.
//

DWORD EnumerateResults(EVT_HANDLE hResults)
{
    //
    // Local Variables
    //

    DWORD status = ERROR_SUCCESS;
    EVT_HANDLE hEvents[EVENT_INDEX ];
    DWORD dwReturned = 0;

    //
    // Beginning of functional Logic
    //
    for (;;)
    {
        while (true)
        {
            //
            // Get a block of events from the result set.
            //
            if (!EvtNext(hResults, EVENT_INDEX , hEvents, INFINITE, 0, &dwReturned))
            {
                if (ERROR_NO_MORE_ITEMS != (status = GetLastError()))
                {
                    wprintf(L"EvtNext failed with %lu\n", status);
                }

                break;
            }

            for (DWORD i = 0; i < dwReturned; i++)
            {
                if (ERROR_SUCCESS == (status = PrintEvent(hEvents[i])))
                {
                    EvtClose(hEvents[i]);
                    hEvents[i] = NULL;
                }
                else
                {
                    break;
                }
            }
        }
        //
        // Final Break Point
        //

        break;
    }

    //
    // Clean up
    //

    for (DWORD i = 0; i < dwReturned; i++)
    {
        if (NULL != hEvents[i])
            EvtClose(hEvents[i]);
    }

    return status;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Delivers the event as an XML string
//

DWORD PrintEvent(EVT_HANDLE hEvent)
{
    //
    // Local Variables
    //

    DWORD status = ERROR_SUCCESS;
    DWORD dwBufferSize = 0;
    DWORD dwBufferUsed = 0;
    DWORD dwPropertyCount = 0;
    LPWSTR pRenderedContent = NULL;

    //
    // Beginning of functional Logic
    //
    for(;;)
    {
        if (!EvtRender(NULL, hEvent, EvtRenderEventValues, dwBufferSize, pRenderedContent, &dwBufferUsed, &dwPropertyCount))
        {
            if (ERROR_INSUFFICIENT_BUFFER == (status = GetLastError()))
            {
                dwBufferSize = dwBufferUsed;
                pRenderedContent = (LPWSTR)malloc(dwBufferSize);
                if (pRenderedContent)
                {
                    EvtRender(NULL, hEvent,EvtRenderEventValues , dwBufferSize, pRenderedContent, &dwBufferUsed, &dwPropertyCount);
                }
                else
                {
                    printf("malloc failed\n");
                    status = ERROR_OUTOFMEMORY;
                    break;
                }
            }

            if (ERROR_SUCCESS != (status = GetLastError()))
            {
                printf("EvtRender failed with %u\n", GetLastError());
                break;
            }
        }

        //
        // Calling WriteEvent
        //

        WriteEvent(pRenderedContent);
        wprintf(L"\n\n%s", pRenderedContent);

        //
        // Final Break Point
        //
        break;
    }

    //
    // Clean up
    //
    if (pRenderedContent)
        free(pRenderedContent);

    return status;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Determines console input key event
//

BOOL IsKeyEvent(HANDLE hStdIn)
{
    INPUT_RECORD Record[128];
    DWORD dwRecordsRead = 0;
    BOOL fKeyPress = FALSE;

    if (ReadConsoleInput(hStdIn, Record, 128, &dwRecordsRead))
    {
        for (DWORD i = 0; i < dwRecordsRead; i++)
        {
            if (KEY_EVENT == Record[i].EventType)
            {
                fKeyPress = TRUE;
                break;
            }
        }
    }
    return fKeyPress;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Writes Event Log to the file
//
void WriteEvent(LPWSTR pRenderedContent)
{
    HANDLE hFile; 
    DWORD dwBytesToWrite = ((DWORD)wcslen(pRenderedContent)*2);
    DWORD dwBytesWritten = 0;
    DWORD dwBytesRead = 0;
    DWORD dwPos = 0;

    BOOL bErrorFlag = FALSE;

    printf("\n");

    hFile = CreateFile(TEXT("D:\\EventsLog.txt"),FILE_APPEND_DATA, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);                 

    if (hFile == INVALID_HANDLE_VALUE) 
    { 
        printf("Terminal failure: Unable to open file \"EventsLog.txt\" for write.\n");
        return;
    }

    printf("Writing %d bytes to EventsLog.txt.\n", dwBytesToWrite);


    bErrorFlag = WriteFile( 
        hFile,                // open file handle
        pRenderedContent,      // start of data to write
        dwBytesToWrite,  // number of bytes to write
        &dwBytesWritten, // number of bytes that were written
        NULL);            // no overlapped structure

    if (FALSE == bErrorFlag)
    {
        printf("Terminal failure: Unable to write to file.\n");
    }
    else
    {
        if (dwBytesWritten != dwBytesToWrite)
        {
            printf("Error: dwBytesWritten != dwBytesToWrite\n");
        }
        else
        {
            printf("Wrote %d bytes to EventsLog.txt successfully.\n",dwBytesWritten);
        }
    }

    CloseHandle(hFile);
}

//-----------------------------------------------------------------------------
// This is the Entry point
//

void main()
{
    DWORD Result;
    Result = InitializeEvent();

    if (ERROR_SUCCESS != Result)
        printf("Initiaize Event Failed %u", GetLastError());
    else
        printf("InitializeEvent Function Returned Successfully");

}
Posted
Updated 12-Feb-22 23:54pm
v2
Comments
dhawal danekhail 24-Sep-13 3:47am    
This is my running code it prints events log in xml style i want it in general event viewer type,tell me where i can make changes to it??
Richard MacCutchan 24-Sep-13 3:56am    
You need to provide more exact details of your problem. I don't think anyone is going to try to figure out what this code does. And please use <pre> tags around your code in future so it is more readable, as I have done for you.
Member 15078716 20-Jul-22 0:43am     CRLF
Maybe change hFile = CreateFile(TEXT("D:\\EventsLog.txt"),FILE_APPEND_DATA, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); to hFile = CreateFile(TEXT("D:\\EventsLog.txt"),FILE_APPEND_DATA, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); Maybe. Maybe not. I ran this through my GCC 5.1 compiler and had so many errors and warnings that I gave up on it. I don't know what to tell you now. OK, I do know what to say, listen to Richard MacCutchan, I do. OK, and I suggest using nullptr instead of NULL where you can to increase executable efficiency. Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900