Search This Blog

12 July 2011

Windows EventLogs with X++

Here's a very small and simple class that makes it very easy to use the Windows EventLogs with X++. It creates, if necessary, a new log/source and logs the events there:
Just derive from the abstract base-class "WinEventLogsBase" (as it is done in WinEventLogs_Batches) and overwrite the log/source and messageId, so that your events are unique.


The job TestEventLogs is an example how to write EventLogs:
static void TestEventLogs(Args _args)
{
    WinEventLogsBase logs;
    System.Diagnostics.EventLogEntryType type = System.Diagnostics.EventLogEntryType::Error;
    System.Int32 eventId = 110;
;
    //Works well, but in the EventLog for Workflow events
    SysWorkflowHelper::writeEventLogEntry("Test simple error from Workflow.");

    //uses the EventSource for the Dynamics Server with the instance suffix to write a message
    System.Diagnostics.EventLog::WriteEntry("Dynamics Server 01", "Test simple error with WriteEntry.");
    //will result in:
    //The description for Event ID ( 0 ) in Source ( Dynamics Server 01 ) cannot be found.
    //because this source is linked to the ressource:
    //C:\Program Files\Microsoft Dynamics AX\50\Server\DynamicsAx1\Bin\Ax32Serv.exe
    //in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Application\Dynamics Server 01
    //which doesn't know how to handle that EventId

    //now by selecting the Dynamics Ax standard EventId 110:
    System.Diagnostics.EventLog::WriteEntry("Dynamics Server 01", "Test simple error with WriteEntry.", type, eventId);
    //Works pretty fine, but: always the same EventSource and EventId, which is not possible to track for many
    //monitoring tools like for example Heroix Longitude which do only interpret the EventId.

    //now that little tool:
    logs = new WinEventLogs_Batches(); //specialization for logs

    //WinEventLogs_Batches uses an EventSource and EventLog on its own
    logs.writeError("Test simple error");  //uses a default EventId
    logs.writeInfo("Test simple info", 4711); //uses an explicit EventId
    logs.writeWarning("Test simple warning");

    logs = new WinEventLogs_Test(); //specialization that uses the Eventlog "Application" for the source

    //WinEventLogs_Test uses its own EventSource but "Application" as EventLog
    logs.writeError("Test simple error");
    logs.writeInfo("Test simple info", 4712);
    logs.writeWarning("Test simple warning");
    //because this tool links the registered EventSource to:
    //c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll
    //it is now possible to use any custom EventId which is not predifined in the resource like in the
    //first example.
}

No comments:

Post a Comment